您的位置:金沙手机版下载 > 澳门官网 > 动态拼接和动态修改

动态拼接和动态修改

2019-10-13 13:47

此第叁遍接触Mybatis框架确实是有一些不适应,非常是刚从Hibernate框架转转型过来,那么为何要运用Mybatis框架,Mybatis框架和Hibernate框架又有啥异同呢?

其一主题素材在自己的另一篇blogs中有特别的上书,今印尼人最首就算带着大家来斟酌一下怎么样轻巧的施用Mybatis这么些框架

大概有些朋友知道,Mybatis中是经过安顿文件来兑现这一个的,那一个中有大多的东西,大家就一点一点的讲啊

咱俩想要配置成功,主要的正是jar包,先从官方网站下载相应的jar包作为程序的协助

 图片 1

有了jar包之后我么就来看看大家前后相继的珍视的搭建

图片 2

具体类的内容如下

Student    Class

package entity;
/*
 * 学生类
 * */
public class Student {
    //学生编号
    private Integer sid;
    //学生名称
    private String sname;
    //学生性别
    private String sex;










    public Student() {
    }
    public Student(String sname, String sex) {
        this.sname = sname;
        this.sex = sex;
    }
    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer sid) {
        this.sid = sid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

}

 

Grade  Class

package entity;
/*
 * 班级类
 * */
public class Grade {
    //班级编号
    private Integer gid;
    //班级名称
    private String gname;
    //班级描述
    private String gdesc;




    public Grade() {
    }
    public Grade(Integer gid, String gname, String gdesc) {
        this.gid = gid;
        this.gname = gname;
        this.gdesc = gdesc;
    }
    public Integer getGid() {
        return gid;
    }
    public void setGid(Integer gid) {
        this.gid = gid;
    }
    public String getGname() {
        return gname;
    }
    public void setGname(String gname) {
        this.gname = gname;
    }
    public String getGdesc() {
        return gdesc;
    }
    public void setGdesc(String gdesc) {
        this.gdesc = gdesc;
    }

}

接下去小编么将要布置大家的严重性配置文件了,主尽管点名大家要连接的数据库和具体连接操作

Configuration.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<!-- 
  <settings>
    <setting name="useGeneratedKeys" value="false"/>
    <setting name="useColumnLabel" value="true"/>
  </settings>

  <typeAliases>
    <typeAlias alias="UserAlias" type="org.apache.ibatis.submitted.complex_property.User"/>
  </typeAliases> -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC">
        <property name="" value=""/>
      </transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="oracle.jdbc.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
        <property name="username" value="practice"/>
        <property name="password" value="123"/>
      </dataSource>
    </environment>
  </environments>

   <mappers>
    <mapper resource="config/Student.xml"/>
  </mappers> 

</configuration>

 

实质上最根本的是如下图所示

图片 3

 

到这里甘休,全数的预备工作多数就早就是水到渠成了

接下去,使用Mybatis框架来贯彻大家的具体操作‘

1.查询全部学生消息

 因为Mybatis是属于一种半自动化的框架能力进而呢sql是大家手动书写的,那也是Mybatis的一大特征

大家得以写出具体的实体配置文件

Student.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Student">

  <resultMap type="entity.Student" id="StudentResult">
    <id column="sid" jdbcType="INTEGER" property="sid"/>
    <result column="sname" jdbcType="VARCHAR" property="sname"/>
    <result column="sex" jdbcType="VARCHAR" property="sex"/>
  </resultMap>

    <select id="selectAllStu"  resultMap="StudentResult">
        select * from Student
    </select>

</mapper>

 

图片 4

既然我们写了sql也钦定了相应的实体类,那么大家到今天停止还并从未采纳它,所以我们还须求在主配置文件中加多实业配置文件的引用

图片 5

 

通过以上的步骤, 我们询问任何上学的儿童的布置文件基本上就已经实现了,今后大家来扩充一道测量检验

/*
     * 1.1 查询所有的学生信息
     * */
    @Test
    public void OneTest() throws Exception{
        //通过配置文件获取到数据库连接信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //通过配置信息构建一个SessionFactory工厂
        SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
        //通过SessionFaction打开一个回话通道
        SqlSession session = sqlsessionfactory.openSession();
        //调用配置文件中的sql语句
        List<Student> list = session.selectList("Student.selectAllStu");
        //遍历查询出来的结果
        for (Student stu : list) {
            System.out.println(stu.getSname());
        }

        session.close();
    }

图片 6

奉行之后的口舌如下

图片 7

 那样我们使用Mybatis查询全体学生音信就完了了

 

2.带条件查询动态Sql拼接

/*
     *1.2 带条件查询信息(动态Sql拼接)
     * */
    @Test
    public void selectAllStuByWhere() throws Exception{
        //通过配置文件获取到数据库连接信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //通过配置信息构建一个SessionFactory工厂
        SqlSessionFactory sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
        //通过SessionFaction打开一个回话通道
        SqlSession session = sqlsessionfactory.openSession();
        //准备一个学生对象作为参数
        Student student=new Student();
        student.setSname("3");
        //调用配置文件中的sql语句
        List<Student> list = session.selectList("Student.selectAllStuByWhere",student);
        //遍历查询出来的结果
        for (Student stu : list) {
            System.out.println(stu.getSname());
        }

        session.close();
    }

 

图片 8

 

小安顿配置文件消息

<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2009-2012 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="Student">

  <resultMap type="entity.Student" id="StudentResult">
    <id column="sid" jdbcType="INTEGER" property="sid"/>
    <result column="sname" jdbcType="VARCHAR" property="sname"/>
    <result column="sex" jdbcType="VARCHAR" property="sex"/>
  </resultMap>

    <!-- 简单查询所有信息 -->
     <select id="selectAllStu"  resultMap="StudentResult">
        select sid,sname,sex,gid from Student 
    </select> 

    <!--动态拼接Sql  -->
     <select id="selectAllStuByWhere" parameterType="entity.Student"  resultMap="StudentResult">
        select sid,sname,sex,gid from Student where 1=1
        <if test="sname!=null and !&quot;&quot;.equals(sname.trim())">
            and sname like '%'|| #{sname}|| '%' <!-- 模糊查询 -->
            <!-- and sname = #{sname} -->
        </if>

     </select>
</mapper>

 图片 9

实行之后的结果便是

图片 10

 

3.新添学生消息

/*
     * 1.3 新增学生信息
     * 
     * */
    @Test
    public void InsertStuInfo() throws Exception{
        //通过配置文件获取配置信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //构建一个SessionFactory,传入配置文件
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        //获取session
        SqlSession session = factory.openSession();
        //准备参数对象
        Student stu=new Student();
        stu.setSname("巴黎的雨季");
        stu.setSex("男");
        //调用添加方法
        int count = session.insert("Student.InsertStuInfo", stu);
        if(count>0){
            System.out.println("添加成功");
        }else{
            System.out.println("添加失败");
        }
        //提交
        session.commit();
        //关闭
        session.close();
    }

 

图片 11

在小布署中加进叁个节点

<!-- 新增学生信息 -->
     <insert id="InsertStuInfo" parameterType="entity.Student" >
         insert into Student values(SEQ_NUM.Nextval,#{sname},#{sex},1)
     </insert>

图片 12

试行之后结果为

图片 13

继续的删减和改造代码基本上和新扩大是同等的,只是调用的sql语句分裂,所以持续小编就不做详细的讲明了,只将代码摆出来,详细大家都能够看得悉道!!

 

4.删减学生消息依附id

/*
     * 1.4根据SID删除学生信息
     * */
    @Test
    public void DeleteStuBySid()throws Exception{
        //通过配置文件获取配置信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //构建一个SessionFactory,传入配置文件
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        //获取session
        SqlSession session = factory.openSession();
        //准备参数
        int sid=2;
        //调用删除方法
        int count = session.delete("Student.DeleteStuBySid", sid);
        if(count>0){
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败");
        }
        //提交
        session.commit();
        //关闭
        session.close();
    }

 

需求在安插文件中新扩张的是

 <!-- 删除学生信息 -->
     <insert id="DeleteStuBySid" parameterType="int">
         delete from Student where sid=#{sid}
     <!--或者是     delete from Student where sid=#{_parameter} -->
     </insert>

 

5.依照SID修改学生音讯

/*
     * 1.5根据SID修改学生信息
     * 
     * */
    @Test
    public void UpdateStuBySid()throws Exception{
        //通过配置文件获取配置信息
        Reader reader = Resources.getResourceAsReader("config/Configuration.xml");
        //构建一个SessionFactory,传入配置文件
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(reader);
        //获取session
        SqlSession session = factory.openSession();
        //准备参数对象
        Student stu=new Student();
        stu.setSid(1);
        stu.setSname("绿茵");
        stu.setSex("女");
        //调用删除方法
        int count = session.update("Student.UpdateStuBySid", stu);
        if(count>0){
            System.out.println("修改成功");
        }else{
            System.out.println("修改失败");
        }
        //提交
        session.commit();
        //关闭
        session.close();
    }

 

须要在铺排文件中增添的是

 

 <!-- 根据SID修改学生信息 -->
     <update id="UpdateStuBySid" parameterType="entity.Student" >
     <!--     update Student set sname=#{sname},sex=#{sex} where sid=#{sid} -->
          update Student
         <set>
             <if test="sname!=null">
                 sname=#{sname},
             </if>
             <if test="sex!=null">
                 sex=#{sex},
             </if>
         </set>
         where sid=#{sid} 
     </update>

 

 

 

  

 以上我们就回顾的做到了对Mybatis的增、删、改、查的基本操作了,关于Mybatis的片段高端内容的执教我会继续在后中为大家一再解说

 

本文由金沙手机版下载发布于澳门官网,转载请注明出处:动态拼接和动态修改

关键词: