Mybatis

MyBatis本是apache的一个开源项目iBatis,2010年这个项目有Apache software foundation 迁移到了Google code,并改名MyBatis.2013年11月迁移到Github。iBatis是半ORM映射框架,它需要在数据库里手动建表,CURD操作时要自己写SQL语句,而Hibernate是全ORM映射框架,它只需要配置好文件,表会自动生成,CURD的SQL语句也是自动生成的,这是他们的主要区别。

MyBatis小巧,简单易学

MyBatis入门案例(综合)

1.1附加架包

1.2编写MyBatis配置文件 mybatis-comfig.xml(由于本人oracle数据库安装的问题端口号及数据库有所不同)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--  别名的配置      Dept-->
    <typeAliases>
        <typeAlias type="cn.mybatis.entity.Dept" alias="Dept"/>
    </typeAliases>
     
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1522:orc" />
                <property name="username" value="bxq" />
                <property name="password" value="bxq" />
            </dataSource>
        </environment>
    </environments>
    <!--关联小配置-->
    <mappers>
        <mapper resource="cn/mybatis/entity/Dept.xml" />
        <mapper resource="cn/mybatis/entity/Dept2.xml" />
    </mappers>
     
 
</configuration>

1.3编写Dept实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package cn.mybatis.entity;
 
public class Dept {
    private Integer deptNo;//部门编号
    private String deptName;//部门名称
    private String deptCity;//部门所在地址
    public String getDeptCity() {
        return deptCity;
    }
    public void setDeptCity(String deptCity) {
        this.deptCity = deptCity;
    }
    public Integer getDeptNo() {
        return deptNo;
    }
    public void setDeptNo(Integer deptNo) {
        this.deptNo = deptNo;
    }
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
    @Override
    public String toString(){
        return "Dept [deptNo= " + deptNo +", deptName=" + deptName+",deptCity"+deptCity+"]";
    }
}

1.4编写Dept.xml小配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.mybatis.entity.Dept">
 
<resultMap type="Dept" id="resultMapper">
    <result property="deptName" column="deptName"/>
    <result property="deptNo" column="deptNo"/>
    <result property="deptCity" column="deptCity"/>
</resultMap>
     <!--代替"*"的方法-->
    <sql id="columns"><br>          <!--植入所需要的列名-->
        deptNo,deptName,deptCity
    </sql>
  <!--++++++++++++++++++++++++++resultMap 实现结果映射++++++++++++++++++++-->
        <!-- 查询部门信息   resultMap 实现结果映射 -->
        <select id="selectAllDeptMapper" resultMap="resultMapper">
            select * from dept
        </select>
        <!-- 代替"*"  连接sql标签的id="columns"-->
        <select id="selectAllDeptUseAlias" resultType="Dept">
            select <include refid="columns"/> from dept
        </select>
 
    <!-- +++++++++++++++++++++++++++++++分割线+++++++++++++++++++++++++++ -->
 
     
    <!-- 1.1查询部门所有信息 -->
        <select id="selectAllDept" resultType="Dept">
        <!--查询所有部门信息  -->
        <!-- SQL不区分大小写 -->
            select * from dept
        </select>
         
    <!-- 增加部门信息 -->
        <insert id="insertDept" parameterType="Dept">
            insert into dept values(#{deptNo},#{deptName},#{deptCity})
        </insert>
         
    <!-- 删除信息 -->
        <delete id="deleteDept" parameterType="Dept">
         
            delete from dept where deptNo=#{deptNo}
        </delete>
         
    <!-- 修改信息 -->
        <update id="updateDept" parameterType="Dept">
         
            update dept set deptName=#{deptName} where deptNo=#{deptNo}
        </update>
         
    <!-- 模糊查询 -->
        <select id="likeDept" parameterType="Dept" resultType="Dept">
         
            select * from dept where deptName like '%${deptName}%'
        </select>
    </mapper>

1.5书写MyTest测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package cn.mybatis.Test;
 
import java.io.IOException;
import java.io.Reader;
import java.util.List;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
 
import cn.mybatis.entity.Dept;
 
public class MyTest {
     
    SqlSession session;
    @Before
    public void initData() throws IOException{
           Reader  reader=Resources.getResourceAsReader("mybatis-config.xml");        
          SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);       
          session= factory.openSession();
    }  
     @Test
       public void testselectAllDept() throws IOException{
          //在xml配置中的一个锁定唯一SQL的id
          List<Dept> selectList = session.selectList("selectAllDept");
          for (Dept dept : selectList) {
              System.out.println(dept);
          }
       }   
     //模糊查詢
    @Test
    public void likeTest(){
        Dept dept = new Dept();
        dept.setDeptName("市场");
        List<Dept> list = session.selectList("cn.mybatis.entity.Dept.likeDept",dept);
        for (Dept item : list) {
            System.out.println(item);
        }
        session.close();
    }
    //修改
    @Test
    public void updateTest(){
        Dept dept = new Dept();
        dept.setDeptNo(5);
        dept.setDeptName("开发部");
        int count = session.update("cn.mybatis.entity.Dept.updateDept",dept);
        session.commit();
        System.out.println(count+"update ok!!!");
        session.close();
    }
    //删除
     @Test
       public void testdeleteDept() throws IOException{
         Dept dept = new Dept();
          dept.setDeptNo(8);
          int count = session.delete("cn.mybatis.entity.Dept.deleteDept",dept);
          session.commit();
          System.out.println(count+"del ok!");
       }
     //增加
     @Test
       public void testinsertDept() throws IOException{
         Dept dept = new Dept();
         dept.setDeptNo(8);
         dept.setDeptName("财务部1");
         dept.setDeptCity("上海");
          int count = session.insert("cn.mybatis.entity.Dept.insertDept",dept);
          session.commit();
          System.out.println(count+"insert ok!!!");
       }
      
      
     /*
      * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      *  resultMap的使用
      */
      
      
    @Test
    public void testresultMap() throws IOException{
        List<Dept> list = session.selectList("cn.mybatis.entity.Dept.selectAllDeptMapper");
        for (Dept dept : list) {
            System.out.println(dept);
        }
        session.close();
    }
    @Test
    public void selectAllDeptUseAlias() throws IOException{
        List<Dept> list = session.selectList("cn.mybatis.entity.Dept.selectAllDeptUseAlias");
        for (Dept dept : list) {
            System.out.println(dept);
        }
        session.close();
    }
      
    /*
     * 动态查询+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     */
    @Test
     public void TestdynamicSelect() throws IOException{
         Dept dept = new Dept();
         dept.setDeptName("市场部");
         dept.setDeptNo(4);
         dept.setDeptCity("北京");
         List<Dept> list = session.selectList("cn.mybatis.dao.IDeptDao.dynamicSelect",dept);
         for (Dept dept2 : list) {
            System.out.println(dept2);
        }
     }
    //动态修改
    @Test
     public void Testdynamicupdate() throws IOException{
         Dept dept = new Dept();
         dept.setDeptName("市场部1");
         dept.setDeptNo(4);
         dept.setDeptCity("北京");
        int count = session.update("cn.mybatis.dao.IDeptDao.dynamicUpdate",dept);
            System.out.println(count);
            session.close();
        }   
}

由于测试方法过多我们简单的运行出来一二个看一下结果

查询:

删除:

2. 动态查询

2.1编写Dept2.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.mybatis.dao.IDeptDao">
    <!-- 1.1查询部门所有信息 -->
        <select id="selectDeptByNo" parameterType="int" resultType="Dept">
        <!--查询所有部门信息  -->
        <!-- SQL不区分大小写 -->
            select * from dept where deptNo=#{deptNo}
        </select>
         
        <select id="getMapper" resultType="Dept">
            select * from dept
        </select>
         
        <!-- 动态查询 -->
        <select id="dynamicSelect" parameterType="Dept" resultType="Dept">
            select * from dept
            <where>
                <if test="deptNo!=null">
                    and deptNo=#{deptNo}
                </if>
                <if test="deptName!=null">
                    and deptName=#{deptName}
                </if>
                <if test="deptCity!=null">
                    and deptCity=#{deptCity}
                </if>
            </where>
        </select>
         
         
        <!-- 动态修改 -->
        <select id="dynamicUpdate" parameterType="int" resultType="Dept">
            update dept
            <set>
                <if test="deptNo!=null">
                     deptNo=#{deptNo},
                </if>
                <if test="deptName!=null">
                     deptName=#{deptName},
                </if>
                <if test="deptCity!=null">
                     deptCity=#{deptCity},
                </if>
            </set>
                where deptNo=#{deptNo}
        </select>
         
         
    </mapper>

2.3在1.5 书写MyTest测试类中可找到我们需要的测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
     * 动态查询+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     */
    @Test
     public void TestdynamicSelect() throws IOException{
         Dept dept = new Dept();
         dept.setDeptName("市场部");
         dept.setDeptNo(4);
         dept.setDeptCity("北京");
         List<Dept> list = session.selectList("cn.mybatis.dao.IDeptDao.dynamicSelect",dept);
         for (Dept dept2 : list) {
            System.out.println(dept2);
        }
     }
    //动态修改
    @Test
     public void Testdynamicupdate() throws IOException{
         Dept dept = new Dept();
         dept.setDeptName("市场部1");
         dept.setDeptNo(4);
         dept.setDeptCity("北京");
        int count = session.update("cn.mybatis.dao.IDeptDao.dynamicUpdate",dept);
            System.out.println(count);
            session.close();
        }  

2.4运行结果

动态查询

动态修改

 3.resultMap实现结果映射

3.1 先前在 1.4编写Dept.xml小配置文件中已经配置好了需要用到的条件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
     * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     *  resultMap的使用
     */
     
     
   @Test
   public void testresultMap() throws IOException{
       List<Dept> list = session.selectList("cn.mybatis.entity.Dept.selectAllDeptMapper");
       for (Dept dept : list) {
           System.out.println(dept);
       }
       session.close();
   }
   @Test
   public void selectAllDeptUseAlias() throws IOException{
       List<Dept> list = session.selectList("cn.mybatis.entity.Dept.selectAllDeptUseAlias");
       for (Dept dept : list) {
           System.out.println(dept);
       }
       session.close();
   }

3.2测试类 与1.5书写MyTest测试类中可见  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
     * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     *  resultMap的使用
     */
     
     
   @Test
   public void testresultMap() throws IOException{
       List<Dept> list = session.selectList("cn.mybatis.entity.Dept.selectAllDeptMapper");
       for (Dept dept : list) {
           System.out.println(dept);
       }
       session.close();
   }
   @Test
   public void selectAllDeptUseAlias() throws IOException{
       List<Dept> list = session.selectList("cn.mybatis.entity.Dept.selectAllDeptUseAlias");
       for (Dept dept : list) {
           System.out.println(dept);
       }
       session.close();
   }

3.3测试结果

1
testresultMap();

1
selectAllDeptUseAlias();

4.session.getMapper()方法

4.1

创建IDeptDao接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package cn.mybatis.dao;
 
import java.util.List;
 
import cn.mybatis.entity.Dept;
/**
 * 接口
 * @author xiaobai
 *
 */
public interface IDeptDao {
    public Dept selectDeptByNo(Integer deptNo);
 
    public List<Dept> getMapper();
}

 4.2编写MyTest2测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package cn.mybatis.Test;
 
import java.io.IOException;
import java.io.Reader;
import java.util.List;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
 
import cn.mybatis.dao.IDeptDao;
import cn.mybatis.entity.Dept;
 
public class MyTest2 {
    SqlSession session;
    @Before
    public void initData() throws IOException{
           Reader  reader=Resources.getResourceAsReader("mybatis-config.xml");        
          SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);       
          session= factory.openSession();
    }  
    //实现getMapper接口<br>     //按条件查询
    @Test
    public void TestgetMapper(){
        IDeptDao mapper = session.getMapper(IDeptDao.class);
        Dept dept = mapper.selectDeptByNo(5);
        System.out.println(dept.getDeptName());
        session.close();
    }
    //查询全部信息
    @Test
    public void TestgetMapper1() throws Exception{
        IDeptDao mapper = session.getMapper(IDeptDao.class);
        List<Dept> list=mapper.getMapper();
        for (Dept dept : list) {
            System.out.println(dept.getDeptName());
        }
    }
     
     
     
}
1
 
1
4.3测试结果:<br>查询全部信息

Mybatis的更多相关文章

  1. mybatis collection 一对多关联查询,单边分页的问题总结!

    若想直接通过sql实现多级关联查询表结构得有2 个必不可少的字段:id ,parentId,levelId id:主键id, parentId:父id levelId:表示第几级(表本身关联查询的时候 ...

  2. mybatis collection的使用

    Mybatis collection的使用 今天学习了mybatis中的collection使用,作为记录以后使用.首先看一下javabean的结构! public class Article {   ...

  3. Mybatis Collection查询集合只出现一条数据

    1.原因 如果两表联查,主表和明细表的主键都是id的话,明细表的多条只能查询出来第一条. 2.解决办法 级联查询的时候,主表和从表有一样的字段名的时候,在mysql上命令查询是没问题的.但在mybat ...

  4. MyBatis collection的两种形式——MyBatis学习笔记之九

    与association一样,collection元素也有两种形式,现介绍如下: 一.嵌套的resultMap 实际上以前的示例使用的就是这种方法,今天介绍它的另一种写法.还是以教师映射为例,修改映射 ...

  5. mybatis <collection>标签 类型为string时无法获取重复数据错误

    1.场景: fyq_share_house 表 和 fyq_sh_tag 表 两张表是一对多的关系, 一个楼盘对应多个标签,在实体类ShareHouse中使用 /** * 楼盘标签 */ privat ...

  6. mybatis collection标签和association标签(一对多,一对一)转载

    mybatis 一对一与一对多collection和association的使用   在mybatis如何进行一对一.一对多的多表查询呢?这里用一个简单的例子说明. 一.一对一 1.associati ...

  7. mybatis collection

    转自:http://blog.csdn.net/wj3319/article/details/9025349 在SQL开发过程中,动态构建In集合条件查询是比较常见的用法,在Mybatis中提供了fo ...

  8. MyBatis Collection小记—— 关联查询、递归查询、多字段关联

    经常会用到mybatis的Collection标签来做级联查询或递归查询,现通过一个伪例来简单的说明一下使用中的关键点: 首先先列出三个表,给出一个场景: 1,角色表 t_role( id,name ...

  9. mybatis collection解析以及和association的区别

    1.collection标签 说到mybatis的collection标签,我们肯定不陌生,可以通过它解决一对多的映射问题,举个例子一个用户对应多个系统权限,通过对用户表和权限表的关联查询我们可以得到 ...

  10. mybatis collection使用注意

    背景 今天我在使用collection时候,出现数据库有两条数据,但是却返回一条,在复制这条数据到四条后,依然返回一条 分析 这四条数据,数据库的每个字段值完全相同,所以估计是当成一条处理了 如果随便 ...

随机推荐

  1. xdebug断点调试原理

    通过Xdebug进行远程调试时,PHPSTORM等IDE会监听Xdebug设置的调试ip和端口(php.ini中配置) [xdebug] ; Xdebug zend_extension=php_xde ...

  2. HTTP的长连接和短连接

        本文总结&分享网络编程中涉及的长连接.短连接概念.     关键字:Keep-Alive,并发连接数限制,TCP,HTTP 一.什么是长连接 HTTP1.1规定了默认保持长连接(HTT ...

  3. 3. 解析 struts.xml 文件

    1. struts.xml 文件基本配置: 主要放在资源路径下,配置 sturts2相关的 Action , 拦截器等配置 <struts> <!-- 设置常量 --> < ...

  4. PhoneGap/cordvoa如何添加Media插件

    phonegap由2.7升级到3.7之前,只要引入一个cordova.js,就可以了.现在由于所用的插件,都需要用模块的形式进行按需加载,自然就没有以前那么安逸了. 例如,如果要在安卓平台添加一个音频 ...

  5. 在C#里面给PPT添加注释

    平常开会或者做总结报告的时候我们通常都会用到PowerPoint演示文稿,我们可以在单个幻灯片或者全部幻灯片里面添加注释,这样观众可以从注释内容里面获取更多的相关信息. 有些朋友不清楚如何在幻灯片里面 ...

  6. Java多种方式动态生成doc文档

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/5280272.html 本来是要在Android端生成doc的(这需求...),最后方法没有好的方法能够在An ...

  7. 来,一起让我们越来越懒,面向CSS、JS未来编程。(9.28已更新)

    2016.10.29更新 本文存在大量的错误,仅供参考. 不知不觉在前端领域马上一个年头就要过去了,然而再看看自己的代码,果然够烂,那么为什么代码一直没有用面向对象的思维去写CSS呢?首先有两点:一点 ...

  8. 『.NET Core CLI工具文档』(十四)dotnet-install 脚本参考

    说明:本文是个人翻译文章,由于个人水平有限,有不对的地方请大家帮忙更正. 原文:dotnet-install scripts reference 翻译:dotnet-install 脚本参考 名称 d ...

  9. linux系统编程之进程(二):进程生命周期与PCB(进程控制块)

    本节目标: 进程状态变迁 进程控制块 进程创建 进程撤消 终止进程的五种方法 一,进程状态变迁 进程的三种基本状态 就绪(Ready)状态 当进程已分配到除CPU以外的所有必要的资源,只要获得处理机便 ...

  10. EL表达式的算术运算

    一个例子--乘法运算 ${book.bookCount * book.bookPrice } 两个不同对象的EL表达式的算术运算同理 ${student.studentNum * book.bookP ...