long blogs

进一步有进一步惊喜


  • Home
  • Archive
  • Tags
  •  

© 2025 long

Theme Typography by Makito

Proudly published with Hexo

Mybatis笔记

Posted at 2019-07-25 笔记 

一、MyBatis的简单使用

1、maven项目依赖

简单的使用Mybatis只需要引入依赖包便可以了。

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

2、需要配置的文件

1、mybatis的配置文件
2、数据库的连接配置文件
3、数据库和Do的实体映射文件

  • mybatis配置文件 configuration.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
<configuration>
<!-- 加载类路径下的属性文件 -->
<properties resource="jdbc.properties"/>
<!-- 设置一个默认的连接环境信息 -->
<environments default="mysql_developer">
<!-- 连接环境信息,取一个任意唯一的名字 -->
<environment id="mysql_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="pooled">
<!-- 配置与数据库交互的4个必要属性 -->
<property name="driver" value="${driverClass}"/>
<property name="url" value="${url}"/>
<property name="username" value="${name}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--将mybatis配置和映射文件关联起来-->
<mappers>
<mapper resource="DictionaryMapper.xml"/>
</mappers>
</configuration>
  • 连接配置文件jdbc.properties
1
2
3
4
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/trainee?useSSL=false
name=root
password=root

相关的配置说明:<properties> resource 加载数据库的相关配置。配置文件和简单的jdbc连接的配置一样。

  • 如何将数据库连接配置文件加载入mybatis配置文件。
    <dataSource type="pooled">使用连接池的方式。连接配置参数是如何将属性加载入mybatis的配置文件。
    dataSource的属性。<property>中的name属性是固定的。需要的是从外部加载进相应的value中。例如
    <property name="driver" value="${driverClass}"/>driverClass便是从连接配置文件加载值的。当然也可以手工给他赋值

  • 实体映射文件。该文件是将数据库中的表和java中的pojo类进行映射和配置相关的操作的。

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
<?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">

<!--
namespace属性是名称空间,必须唯一
可以自定义
-->
<mapper namespace="DictionarySpace">
<resultMap id="dictionaryMap" type="com.bosssoft.hr.train.chp2.pojo.entity.Dictionary">
<id property="categoryId" column="category_id"/>
<result property="name" column="name" />
<result property="category" column="category" />
<result property="value" column="value" />
<result property="remark" column="remark"/>
<result property="status" column="status"/>
<result property="orgId" column="org_id"/>
<result property="createdBy" column="created_by"/>
<result property="createdTime" column="created_time"/>
<result property="updatedBy" column="updated_by"/>
<result property="updatedTime" column="updated_time"/>
<result property="version" column="version"/>
</resultMap>

<!--增-->
<insert id="insertDictionary" parameterType="com.bosssoft.hr.train.chp2.pojo.entity.Dictionary">
INSERT INTO t_dictionary (category_id,name,category,value,remark,status,org_id,
created_by,created_time,updated_by,updated_time,version) values
(#{categoryId},#{name},#{category},#{value},#{remark},#{status},#{orgId},
#{createdBy},#{createdTime},#{updatedBy},#{updatedTime},#{version});
</insert>
<!--删-->
<delete id="deleteDictionary" parameterType="long">
DELETE FROM t_dictionary WHERE category_id = #{id};
</delete>
<!--查-->
<select id="queryDictionary" parameterType="long" resultMap="dictionaryMap">
SELECT * FROM t_dictionary WHERE category_id = #{id};
</select>

<!--改-->
<update id="updateDictionary" parameterType="com.bosssoft.hr.train.chp2.pojo.entity.Dictionary">
UPDATE t_dictionary SET name=#{name},category=#{category},value=#{value},remark=#{remark},status=#{status},org_id=#{orgId},
created_by=#{createdBy},created_time=#{createdTime},updated_by=#{updatedBy},updated_time=#{updatedTime},version=#{version}
WHERE category_id = #{categoryId};
</update>
</mapper>

相关属性说明:

  • mapper 中的namespace 命名空间。
    作用是让mybatis的sqlsession找到该空间下的sql语句来执行。
    sqlSession.insert("DictionarySpace.insertDictionary",dictionary);
  • resultMap
    这是最重要的配置项。该项连接了数据库的表项和java的实体类。
    (1)resultMap#id 标识唯一的值。该值可以被引用。
    (2)resultMap#type 对应的java类。
    (3)<id> key值。其中的 property是对应的POJO类的属性。column是对应的数据表中的字段值。
  • sql语句
    相关属性说明
    (1) id 该sql语句的唯一标识符。和命名空间一起被唯一的调用。
    (2) parameterType 参数的类型。这个是入口参数类型。可以是基本的数据类型,也可以是自己的类。
    (3) resultMap 返回的数据对象。和前面的resultMap相对应。这样在代码中便可以获得该返回对象了。

将该配置文件和Mybatis的配置文件关联起来需要在configuration.xml中引入该mapper.

1
2
3
4
<!--将mybatis配置和映射文件关联起来-->
<mappers>
<mapper resource="DictionaryMapper.xml"/>
</mappers>

1对多返回的部分数据中存储为list
使用如下的格式返回list数据

1
2
3
<collection property="roles" ofType="java.lang.String" javaType="java.util.List">
<result column="role_name" />
</collection>

3、Mybatis加载过程。

基本流程如下:
1、读取configuration.xml -> 加载连接配置jdbc.properties -> 获得连接对象SqlSession

1
2
3
4
5
6
7
8
static {
try {
Reader reader = Resources.getResourceAsReader("configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
}

返回连接对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 获取SqlSession
*/
public static SqlSession getSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象为空
if(sqlSession == null){
//在SqlSessionFactory非空的情况下,获取SqlSession对象
sqlSession = sqlSessionFactory.openSession();

//将SqlSession对象与当前线程绑定在一起
threadLocal.set(sqlSession);
}
//返回SqlSession对象
return sqlSession;
}

2、使用SqlSession对象来调用sql语句,configuration.xml 知道mapper位置 -> mapper命名空间的和sql的id -> 加载语句执行
简单的插入语句的操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param dictionary 待插入的字典
* @return 返回插入结果
* @throws Exception 可能会抛出异常
*/
public boolean insertDictionary(Dictionary dictionary) throws Exception {
SqlSession sqlSession = MybatisUtil.getSqlSession();
boolean returnStatus = false;
try {
sqlSession.insert("DictionarySpace.insertDictionary",dictionary);
sqlSession.commit();
returnStatus = true;
} catch (Exception e) {
sqlSession.rollback();
throw e;
} finally {
MybatisUtil.closeSqlSession();
}
return returnStatus;
}

4、完整的源代码

1、configration.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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 加载类路径下的属性文件 -->
<properties resource="jdbc.properties"/>
<!-- 设置一个默认的连接环境信息 -->
<environments default="mysql_developer">
<!-- 连接环境信息,取一个任意唯一的名字 -->
<environment id="mysql_developer">
<!-- mybatis使用jdbc事务管理方式 -->
<transactionManager type="jdbc"/>
<!-- mybatis使用连接池方式来获取连接 -->
<dataSource type="pooled">
<!-- 配置与数据库交互的4个必要属性 -->
<property name="driver" value="${driverClass}"/>
<property name="url" value="${url}"/>
<property name="username" value="${name}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--将mybatis配置和映射文件关联起来-->
<mappers>
<mapper resource="DictionaryMapper.xml"/>
</mappers>
</configuration>

2、DictionaryMapper.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
<?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">

<!--
namespace属性是名称空间,必须唯一
可以自定义
-->
<mapper namespace="DictionarySpace">
<resultMap id="dictionaryMap" type="com.bosssoft.hr.train.chp2.pojo.entity.Dictionary">
<id property="categoryId" column="category_id"/>
<result property="name" column="name" />
<result property="category" column="category" />
<result property="value" column="value" />
<result property="remark" column="remark"/>
<result property="status" column="status"/>
<result property="orgId" column="org_id"/>
<result property="createdBy" column="created_by"/>
<result property="createdTime" column="created_time"/>
<result property="updatedBy" column="updated_by"/>
<result property="updatedTime" column="updated_time"/>
<result property="version" column="version"/>
</resultMap>

<!--增-->
<insert id="insertDictionary" parameterType="com.bosssoft.hr.train.chp2.pojo.entity.Dictionary">
INSERT INTO t_dictionary (category_id,name,category,value,remark,status,org_id,
created_by,created_time,updated_by,updated_time,version) values
(#{categoryId},#{name},#{category},#{value},#{remark},#{status},#{orgId},
#{createdBy},#{createdTime},#{updatedBy},#{updatedTime},#{version});
</insert>
<!--删-->
<delete id="deleteDictionary" parameterType="long">
DELETE FROM t_dictionary WHERE category_id = #{id};
</delete>
<!--查-->
<select id="queryDictionary" parameterType="long" resultMap="dictionaryMap">
SELECT * FROM t_dictionary WHERE category_id = #{id};
</select>

<!--改-->
<update id="updateDictionary" parameterType="com.bosssoft.hr.train.chp2.pojo.entity.Dictionary">
UPDATE t_dictionary SET name=#{name},category=#{category},value=#{value},remark=#{remark},status=#{status},org_id=#{orgId},
created_by=#{createdBy},created_time=#{createdTime},updated_by=#{updatedBy},updated_time=#{updatedTime},version=#{version}
WHERE category_id = #{categoryId};
</update>
</mapper>

3、MybatisUtil.java

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
package com.bosssoft.hr.train.chp2.util;

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.apache.log4j.Logger;

import java.io.IOException;
import java.io.Reader;


/**
* 工具类
* @author longquanxiao
* @date 2019/7/24
*
*/
public class MybatisUtil {
/**
* 本地线程
*/
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

/**
* SqlSessionFactory 工厂
*/
private static SqlSessionFactory sqlSessionFactory;

/**
* 日志对象
*/
private static Logger logger = Logger.getLogger(MybatisUtil.class);
static{
try {
Reader reader = Resources.getResourceAsReader("configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
}
/**
* 禁止外界通过new方法创建
*/
private MybatisUtil(){}

/**
* 获取SqlSession
*/
public static SqlSession getSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象为空
if(sqlSession == null){
//在SqlSessionFactory非空的情况下,获取SqlSession对象
sqlSession = sqlSessionFactory.openSession();

//将SqlSession对象与当前线程绑定在一起
threadLocal.set(sqlSession);
}
//返回SqlSession对象
return sqlSession;
}
/**
* 关闭SqlSession与当前线程分开
*/
public static void closeSqlSession(){
//从当前线程中获取SqlSession对象
SqlSession sqlSession = threadLocal.get();
//如果SqlSession对象非空
if(sqlSession != null){
//关闭SqlSession对象
sqlSession.close();
//分开当前线程与SqlSession对象的关系,目的是让GC尽早回收
threadLocal.remove();
}
}
}

4、Dao 的接口类 IDictionaryDao.java

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
package com.bosssoft.hr.train.chp2.dao;

import com.bosssoft.hr.train.chp2.pojo.entity.Dictionary;

/**
* 数据字典的接口类
* @author longquanxiao
* @date 2019/7/24
*/
public interface IDictionaryDao {

/**
* 插入dictionary数据
* @param dictionary 输入的参数
* @return 返回执行的结果 true / false
* @throws Exception 可能会抛出异常
*/
boolean insertDictionary(Dictionary dictionary) throws Exception;

/**
* 更新数据字典
* @param dictionary 待修改的字典
* @return 修改的结果 true / false
* @throws Exception 异常抛出
*/
boolean updateDictionary(Dictionary dictionary) throws Exception ;


/**
* 根据id 获得dictionary
* @param id 查询的id
* @return 返回查询的结果
* @throws Exception 可能会返回异常
*/
Dictionary queryDictionary(long id) throws Exception;

/**
* 根据id删除字典
* @param id 待删除的id
* @return 删除结果 true / false
* @throws Exception 异常抛出
*/
boolean deleteDictionaryById(long id) throws Exception;
}

5、实现类 DictionaryDaoImpl.java

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
package com.bosssoft.hr.train.chp2.dao.impl;

import com.bosssoft.hr.train.chp2.dao.IDictionaryDao;
import com.bosssoft.hr.train.chp2.pojo.entity.Dictionary;
import com.bosssoft.hr.train.chp2.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

/**
* 接口实现类
* @author longquanxiao
* @date 2019/7/24
*/
public class DictionaryDaoImpl implements IDictionaryDao {
/**
* @param dictionary 待插入的字典
* @return 返回插入结果
* @throws Exception 可能会抛出异常
*/
public boolean insertDictionary(Dictionary dictionary) throws Exception {
SqlSession sqlSession = MybatisUtil.getSqlSession();
boolean returnStatus = false;
try {
sqlSession.insert("DictionarySpace.insertDictionary",dictionary);
sqlSession.commit();
returnStatus = true;
} catch (Exception e) {
sqlSession.rollback();
throw e;
} finally {
MybatisUtil.closeSqlSession();
}
return returnStatus;
}

/**
* @param dictionary 待修改的字典
* @return 修改的结果
* @throws Exception 可能会抛出异常
*/
public boolean updateDictionary(Dictionary dictionary) throws Exception {
SqlSession sqlSession = MybatisUtil.getSqlSession();
boolean returnStatus = false;
try{
sqlSession.update("DictionarySpace.updateDictionary",dictionary);
sqlSession.commit();
returnStatus = true;
}catch (Exception e){
// 回滚
sqlSession.rollback();
throw e;
}finally {
MybatisUtil.closeSqlSession();
}
return returnStatus;
}


/**
* @param id 查询的id
* @return 返回查询的结果,可能为空
* @throws Exception 异常
*/
public Dictionary queryDictionary(long id) throws Exception {
Dictionary returnDictionary = null;
try {
SqlSession sqlSession = MybatisUtil.getSqlSession();
returnDictionary = sqlSession.selectOne("DictionarySpace.queryDictionary",id);
} catch (Exception e) {
throw e;
} finally {
MybatisUtil.closeSqlSession();
}
return returnDictionary;
}

/**
* @param id 待删除的id
* @return 删除的结果
* @throws Exception 抛出的异常
*/
public boolean deleteDictionaryById(long id) throws Exception {
boolean returnStatus=false;
SqlSession sqlSession = MybatisUtil.getSqlSession();

try{
if(sqlSession != null) {
sqlSession.delete("DictionarySpace.deleteDictionary", id);
sqlSession.commit();
returnStatus = true;
}
}catch (Exception e){
sqlSession.rollback();
throw e;
}finally {
MybatisUtil.closeSqlSession();
}
return returnStatus;
}
}

6、实体类 Dictionary.java

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
package com.bosssoft.hr.train.chp2.pojo.entity;

import java.util.Date;

/**
* 数据字典的DO
* @author longquanxiao
* @date 2019/7/24
*/
public class Dictionary {
/**
* 数据字典ID
*/
private long categoryId;
/**
* 字典名
*/
private char name;
/**
* 字典类型
*/
private char category;
/**
* 字典值
*/
private char value;
/**
* 备注
*/
private String remark;
/**
* 状态位
*/
private byte status;
/**
* 机构ID
*/
private long orgId;
/**
* 创建人
*/
private long createdBy;
/**
* 创建时间
*/
private Date createdTime;
/**
* 修改人
*/
private long updatedBy;
/**
* 修改时间
*/
private Date updatedTime;
/**
* 版本
*/
private long version;

/**getter setter**/
}

7、测试类

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

/**
* @author longquanxiao
* @date 2019/7/24
*/
public class DictionaryDaoImplTest extends TestCase {
/**
* 日志
*/
private static Logger logger = Logger.getLogger(DictionaryDaoImplTest.class);

/**
* 测试插入数据
*/
public void testInsertDictionary() {
IDictionaryDao dao = new DictionaryDaoImpl();
Dictionary insertDictionary = new Dictionary();
// 设置属性
insertDictionary.setCategoryId(10);
insertDictionary.setName('2');
insertDictionary.setCategory('2');
insertDictionary.setValue('2');
insertDictionary.setRemark("test insert");
byte i = 1;
insertDictionary.setStatus(i);

insertDictionary.setOrgId(12);
insertDictionary.setCreatedBy(1);
Date iDate = new Date();
System.out.println(iDate);
insertDictionary.setCreatedTime(iDate);

insertDictionary.setUpdatedTime(iDate);
insertDictionary.setVersion(1);
//
try {
if(dao.insertDictionary(insertDictionary)){
System.out.println("插入数据成功");
}else {
System.out.println("插入数据失败");
}
}catch (Exception e){
logger.error(e.getMessage(),e);
}
}

/**
* 测试更新数据
*/
public void testUpdateDictionary() {
// 先查后改
IDictionaryDao dao = new DictionaryDaoImpl();
Dictionary updateDictionary = null;
try {
updateDictionary = dao.queryDictionary(1);
if( updateDictionary != null){
updateDictionary.setRemark("update");
Date idate = new Date();
updateDictionary.setUpdatedTime(idate);
// 调用更新函数进行更新
if (dao.updateDictionary(updateDictionary)) {
System.out.println("更新成功");
} else {
System.out.println("更新失败");
}
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
}

/**
* 查询数据
*/
public void testQueryDictionary() {
IDictionaryDao dao = new DictionaryDaoImpl();
Dictionary queryDictionary = null;
try {
queryDictionary= dao.queryDictionary(1);
if (queryDictionary!=null){
System.out.println("查询数据成功");
System.out.println("name:"+queryDictionary.getName());
System.out.println("created_time="+queryDictionary.getCreatedTime());
}else{
System.out.println("查询数据失败");
}
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
}

/**
* 删除数据
*/
public void testDeleteDictionaryById() {
IDictionaryDao dao = new DictionaryDaoImpl();
try {
// 删除id为10的数据
if(dao.deleteDictionaryById(10)){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
}catch (Exception e){
logger.error(e.getMessage(),e);
}
}
}

规范化的测试。使用断言,不用捕获异常。

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
package com.bosssoft.hr.train.chp2.dao.impl;

import com.bosssoft.hr.train.chp2.dao.IDictionaryDao;
import com.bosssoft.hr.train.chp2.pojo.entity.Dictionary;
import junit.framework.TestCase;

import java.util.Date;


/**
* @author longquanxiao
* @date 2019/7/24
*/
public class DictionaryDaoImplTest extends TestCase {
/**
* 测试插入数据
*/
public void testInsertDictionary() throws Exception{
IDictionaryDao dao = new DictionaryDaoImpl();
Dictionary insertDictionary = new Dictionary();
// 设置属性
insertDictionary.setCategoryId(10);
insertDictionary.setName('2');
insertDictionary.setCategory('2');
insertDictionary.setValue('2');
insertDictionary.setRemark("test insert");
byte i = 1;
insertDictionary.setStatus(i);

insertDictionary.setOrgId(12);
insertDictionary.setCreatedBy(1);
Date iDate = new Date();
insertDictionary.setCreatedTime(iDate);

insertDictionary.setUpdatedTime(iDate);
insertDictionary.setVersion(1);
assertTrue(dao.insertDictionary(insertDictionary));
}

/**
* 测试更新数据
*/
public void testUpdateDictionary() throws Exception{
// 先查后改
IDictionaryDao dao = new DictionaryDaoImpl();
Dictionary updateDictionary = null;
updateDictionary = dao.queryDictionary(1);

assertNotNull(updateDictionary);
updateDictionary.setRemark("update");
Date idate = new Date();
updateDictionary.setUpdatedTime(idate);
// 调用更新函数进行更新
assertTrue(dao.updateDictionary(updateDictionary));
}

/**
* 查询数据
*/
public void testQueryDictionary() throws Exception{
IDictionaryDao dao = new DictionaryDaoImpl();
Dictionary queryDictionary = null;
queryDictionary= dao.queryDictionary(1);
assertNotNull(queryDictionary);
}

/**
* 删除数据
*/
public void testDeleteDictionaryById() throws Exception {
IDictionaryDao dao = new DictionaryDaoImpl();
// 删除id为10的数据
assertTrue(dao.deleteDictionaryById(10));
}
}

二、SpringBoot 整合Mybatis

1、application.properties配置mybatis

1
2
3
4
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/trainee?serverTimezone=GMT%2B8
spring.datasource.username=username
spring.datasource.password=password

2、使用接口来定义一个Dao层

相比于传统的xml的配置文件来映射数据库实体文件。SpirngBoot只需要注解便可以实现java到实体的映射

2.1 常用注解
  • @Insert()插入语句的注解
    例子:
1
2
3
4
5
@Insert("INSERT INTO t_dictionary (category_id,name,category,value,remark,status,org_id," +
"created_by,created_time,updated_by,updated_time,version) values" +
"(#{categoryId},#{name},#{category},#{value},#{remark},#{status},#{orgId}," +
"#{createdBy},#{createdTime},#{updatedBy},#{updatedTime},#{version}) ")
int insertDictionary(Dictionary dictionary);

注意#{}使用预编译的字符填充。填充的字符和dictionary中的成员一致。

  • @Select()查询语句,需要指定返回值类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Select("SELECT * FROM t_dictionary")
@Results(id = "dictionaryMap",value = {
@Result(id = true,column = "category_id",property = "categoryId"),
@Result(column = "name",property = "name"),
@Result(column = "category",property = "category"),
@Result(column = "value",property = "value"),
@Result(column = "remark",property = "remark"),
@Result(property="status",column="status"),
@Result(property="orgId",column="org_id"),
@Result(property="createdBy",column="created_by"),
@Result(property="createdTime",column="created_time"),
@Result(property="updatedBy", column="updated_by"),
@Result(property="updatedTime", column="updated_time"),
@Result(property="version" ,column="version")
})
List<Dictionary> queryAll();

@Results是返回值的类型。如果没有定义过的话就要自己定义一个。id是该result的标识符。property是java实体的成员。column是数据库表中的列。

  • 使用上面定义好的Results
1
2
3
@Select("SELECT * FROM t_dictionary WHERE name=#{name} AND category=#{category} AND status=#{status}")
@ResultMap("dictionaryMap")
List<Dictionary> queryByNameTypeStatus(String name,String category, byte status);

注解中的@ResultMap(id)使用已定义的Results id = dictionaryMap

  • 更新的注解 @Update()
1
2
3
4
@Update("UPDATE t_dictionary SET name=#{name},category=#{category},value=#{value},remark=#{remark},status=#{status},org_id=#{orgId}," +
"created_by=#{createdBy},created_time=#{createdTime},updated_by=#{updatedBy},updated_time=#{updatedTime}, version=#{version}" +
" WHERE category_id = #{categoryId}")
int updateDictionary(Dictionary dictionary);
  • 删除的注解@Delete()
1
2
@Delete("DELETE FROM t_dictionary WHERE category_id = #{id}")
int deleteDictionary(long id);
2.2 启动类中扫描相关的组件

@MapperScan("com.bosssoft.hr.train.chp2.dao")扫描为dao

3、使用Dao来进行访问

1
2
3
4
5
/**
* dao对象
*/
@Resource
private DictionaryDao dictionaryDao;

Share 

 Previous post: 单元测试unit Next post: Ideas使用的坑 

© 2025 long

Theme Typography by Makito

Proudly published with Hexo