初识Mybatis框架,实现增删改查等操作(动态拼接和动态修改)

此第一次接触 Mybatis 框架确实是有点不适应,特别是刚从 Hibernate 框架转转型过来,那么为什么要使用 Mybatis 框架,Mybatis 框架和 Hibernate 框架又有什么异同呢?

这个问题在我的另一篇 blogs 中有专门的讲解,今天我主要是带着大家来探讨一下如何简单的使用 Mybatis 这个框架

可能有的朋友知道,Mybatis 中是通过配置文件来实现这个的,这里面有很多的东西,我们就一点一点的讲吧

我们想要配置成功,首要的就是 jar 包,先从官网下载相应的 jar 包作为程序的支撑

 

有了 jar 包之后我么就来看看我们程序的主要的搭建

具体类的内容如下

Student    Class

package entity;
/*
 * 学生类
 * */
public class Student {
    //学生编号
    private Integer sid;
    //学生名称
    private String sname;
    //学生性别
    private String sex;
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Student() {
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Student(String sname, String sex) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.sname =<span style="color: rgba(0, 0, 0, 1)"> sname;
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.sex =<span style="color: rgba(0, 0, 0, 1)"> sex;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Integer getSid() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sid;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setSid(Integer sid) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.sid =<span style="color: rgba(0, 0, 0, 1)"> sid;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getSname() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sname;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setSname(String sname) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.sname =<span style="color: rgba(0, 0, 0, 1)"> sname;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getSex() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sex;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setSex(String sex) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.sex =<span style="color: rgba(0, 0, 0, 1)"> sex;
}

}

 

Grade  Class

package entity;
/*
 * 班级类
 * */
public class Grade {
    //班级编号
    private Integer gid;
    //班级名称
    private String gname;
    //班级描述
    private String gdesc;
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Grade() {
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Grade(Integer gid, String gname, String gdesc) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.gid =<span style="color: rgba(0, 0, 0, 1)"> gid;
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.gname =<span style="color: rgba(0, 0, 0, 1)"> gname;
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.gdesc =<span style="color: rgba(0, 0, 0, 1)"> gdesc;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Integer getGid() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> gid;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setGid(Integer gid) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.gid =<span style="color: rgba(0, 0, 0, 1)"> gid;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getGname() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> gname;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setGname(String gname) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.gname =<span style="color: rgba(0, 0, 0, 1)"> gname;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getGdesc() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> gdesc;
}
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setGdesc(String gdesc) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.gdesc =<span style="color: rgba(0, 0, 0, 1)"> gdesc;
}

}

接下来我么就要配置我们的主要配置文件了,主要是指定我们要连接的数据库和具体连接操作

Configuration.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!--
   Copyright </span><span style="color: rgba(128, 0, 128, 1)">2009</span>-<span style="color: rgba(128, 0, 128, 1)">2012</span><span style="color: rgba(0, 0, 0, 1)"> the original author or authors.

   Licensed under the Apache License, Version </span><span style="color: rgba(128, 0, 128, 1)">2.0</span> (the <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">License</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
   you may not use </span><span style="color: rgba(0, 0, 255, 1)">this</span> file except <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> compliance with the License.
   You may obtain a copy of the License at

      http:</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">www.apache.org/licenses/LICENSE-2.0</span>
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>

 

其实最主要的是如下图所示

 

到这里为止,所有的准备工作基本上就已经是完成了

接下来,使用 Mybatis 框架来实现我们的具体操作‘

1. 查询所有学生信息

 因为 Mybatis 是属于一种半自动化的框架技术所以呢 sql 是我们手动书写的,这也是 Mybatis 的一大特点

我们可以写出具体的实体配置文件

Student.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
   Copyright </span><span style="color: rgba(128, 0, 128, 1)">2009</span>-<span style="color: rgba(128, 0, 128, 1)">2012</span><span style="color: rgba(0, 0, 0, 1)"> the original author or authors.

   Licensed under the Apache License, Version </span><span style="color: rgba(128, 0, 128, 1)">2.0</span> (the <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">License</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
   you may not use </span><span style="color: rgba(0, 0, 255, 1)">this</span> file except <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> compliance with the License.
   You may obtain a copy of the License at

      http:</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">www.apache.org/licenses/LICENSE-2.0</span>
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>

&lt;<span style="color: rgba(0, 0, 255, 1)">select</span> id=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">selectAllStu</span><span style="color: rgba(128, 0, 0, 1)">"</span>  resultMap=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">StudentResult</span><span style="color: rgba(128, 0, 0, 1)">"</span>&gt;
    <span style="color: rgba(0, 0, 255, 1)">select</span> * <span style="color: rgba(0, 0, 255, 1)">from</span><span style="color: rgba(0, 0, 0, 1)"> Student
</span>&lt;/<span style="color: rgba(0, 0, 255, 1)">select</span>&gt;

</mapper>

 

既然我们写了 sql 也指定了相应的实体类,那么我们到现在为止还并没有用到它,所以我们还需要在主配置文件中添加实体配置文件的引用

 

经过以上的步骤, 我们查询全部学生的配置文件基本上就已经完成了,现在我们来进行一道测试

/*
     * 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();
}</span></pre>

执行之后的语句如下

 这样我们使用 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();
}</span></pre>

 

 

小配置配置文件信息

<?xml version="1.0" encoding="UTF-8"?>
<!--
   Copyright </span><span style="color: rgba(128, 0, 128, 1)">2009</span>-<span style="color: rgba(128, 0, 128, 1)">2012</span><span style="color: rgba(0, 0, 0, 1)"> the original author or authors.

   Licensed under the Apache License, Version </span><span style="color: rgba(128, 0, 128, 1)">2.0</span> (the <span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">License</span><span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(0, 0, 0, 1)">);
   you may not use </span><span style="color: rgba(0, 0, 255, 1)">this</span> file except <span style="color: rgba(0, 0, 255, 1)">in</span><span style="color: rgba(0, 0, 0, 1)"> compliance with the License.
   You may obtain a copy of the License at

      http:</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">www.apache.org/licenses/LICENSE-2.0</span>
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>

&lt;!-- 简单查询所有信息 --&gt;
 &lt;<span style="color: rgba(0, 0, 255, 1)">select</span> id=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">selectAllStu</span><span style="color: rgba(128, 0, 0, 1)">"</span>  resultMap=<span style="color: rgba(128, 0, 0, 1)">"</span><span style="color: rgba(128, 0, 0, 1)">StudentResult</span><span style="color: rgba(128, 0, 0, 1)">"</span>&gt;
    <span style="color: rgba(0, 0, 255, 1)">select</span> sid,sname,sex,gid <span style="color: rgba(0, 0, 255, 1)">from</span><span style="color: rgba(0, 0, 0, 1)"> Student 
</span>&lt;/<span style="color: rgba(0, 0, 255, 1)">select</span>&gt; 

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

</mapper>

 

执行之后的结果就是

 

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();}

 

在小配置中增加一个节点

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

执行之后结果为

后续的删除和修改代码基本上和新增是一致的,只是调用的 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 的一些高级内容的讲解我会继续在后中为大家持续讲解