mybatis 的常用注解

注解 说明
@Insert 实现新增
@Delete 实现删除
@Update 实现更新
@Select 实现查询
@Result 实现结果集封装
@Results 可以与@Result 一起使用,封装多个结果集
@ResultMap 实现引用@Results 定义的封装
@One 实现一对一结果集封装
@Many 实现一对多结果集封装
@SelectProvider 实现动态 SQL 映射
@CacheNamespace 实现注解二级缓存的使用

使用 Mybatis 注解实现基本 CRUD

项目目录结构

编写实体类

User:

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
package com.keafmd.domain;

import java.io.Serializable;
import java.util.Date;

/**
* Keafmd
*
* @ClassName: User
* @Description: User实体类
* @author: SerMs
* @date: 2022-02-16 20:28
*/
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}

使用注解方式开发持久层接口

IUserDao:

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.keafmd.dao;

import com.keafmd.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
* Keafmd
*
* @ClassName: IUserDao
* @Description:
* @author: SerMs
* @date: 2022-02-16 20:30
*/

/**
* 在mybatis中针对CRUD一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {

/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List<User> findAll();

/**
* 保存用户
* @param user
*/
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);

/**
* 更新用户
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
void updateUser(User user);

/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id=#{id}")
void deleteUser(Integer userId);

/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id}")
User findById(Integer userId);

/**
* 根据用户名称模糊查询
* @param username
* @return
*/
//@Select("select * from user where username like #{username}") //占位符
@Select("select * from user where username like '%${value}%'") //字符串拼接
List<User> findByName(String username);

/**
* 查询总数量
* @return
*/
@Select("select count(*) from user")
int findTotal();

}

通过注解方式,就不需要再去编写 UserDao.xml 映射文件了。

编写 SqlMapConfig.xml 配置文件

SqlMapConfig.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
<?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="jdbcConfig.properties"></properties>
<!--配置别名-->
<typeAliases>
<package name="com.keafmd.domain"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<!--指定带有注解的dao接口所在位置-->
<mappers>
<package name="com.keafmd.dao"></package>
</mappers>
</configuration>

编写测试代码

AnnotationCRUDTest:

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
package com.keafmd.test;

import com.keafmd.dao.IUserDao;
import com.keafmd.domain.User;
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.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
* Keafmd
*
* @ClassName: AnnotationCRUDTest
* @Description: 注解开发CRUD测试
* @author: SerMs
* @date: 2022-02-16 21:05
*/
public class AnnotationCRUDTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;

@Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class);
}

@After
public void destory() throws Exception{
session.commit();
session.close();
in.close();
}

@Test
public void testSave(){
User user = new User();
user.setUsername("mybatis annotation");
user.setAddress("北京");

userDao.saveUser(user);
}

@Test
public void testUpdate(){
User user = new User();
user.setId(55);
user.setUsername("mybatis annotation");
user.setAddress("北京");
user.setSex("男");
user.setBirthday(new Date());

userDao.updateUser(user);
}

@Test
public void testDelete(){
userDao.deleteUser(54);
}

@Test
public void testFindOne(){
User user = userDao.findById(55);
System.out.println(user);
}

@Test
public void testFindByName(){
//List<User> users = userDao.findByName("%Keafmd%");
List<User> users = userDao.findByName("Keafmd");
for (User user : users) {
System.out.println(user);
}
}

@Test
public void testFindTotal(){
int total = userDao.findTotal();
System.out.println(total);
}
}

使用注解实现复杂关系映射开发

实现复杂关系映射之前我们可以在映射文件中通过配置<resultMap>来实现,在使用注解开发时我们需要借助@Results 注解,@Result 注解,@One 注解,@Many 注解。

复杂关系映射的注解说明

@Results 注解
代替的是标签<resultMap>
该注解中可以使用单个@Result 注解,也可以使用@Result 集合
@Results({@Result(),@Result()})或@Results(@Result())

@Resutl 注解
代替了<id> 标签和<result>标签
@Result 中的属性介绍:

@Result 中的属性 介绍
id 是否是主键字段
column 数据库的列名
property 需要装配的属性名
one 需要使用的@One 注解(@Result(one=@One)()))
many 需要使用的@Many 注解(@Result(many=@many)()))

@One 注解(一对一)
代替了标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。
@One 注解属性介绍:
select 指定用来多表查询的 sqlmapper
fetchType 会覆盖全局的配置参数 lazyLoadingEnabled。
使用格式:@Result(column=” “,property=””,one=@One(select=””))

@Many 注解(多对一)
代替了标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。
注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType(一般为 ArrayList)但是注解中可以不定义。
使用格式:@Result(property=””,column=””,many=@Many(select=””))

项目目录

使用注解实现一对一复杂关系映射及立即加载

需求:加载账户信息时并且加载该账户的用户信息,根据情况可实现立即加载。(注解方式实现)

添加 User 实体类及 Account 实体类

User:

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
package com.keafmd.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
* Keafmd
*
* @ClassName: User
* @Description: User实体类
* @author: SerMs
* @date: 2022-02-16 20:28
*/
public class User implements Serializable {
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getUserAddress() {
return userAddress;
}

public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}

public String getUserSex() {
return userSex;
}

public void setUserSex(String userSex) {
this.userSex = userSex;
}

public Date getUserBirthday() {
return userBirthday;
}

public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}

@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddress='" + userAddress + '\'' +
", userSex='" + userSex + '\'' +
", userBirthday=" + userBirthday +
'}';
}
}

Account:

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
package com.keafmd.domain;

import java.io.Serializable;

/**
* Keafmd
*
* @ClassName: Account
* @Description: 账户实体类
* @author: SerMs
* @date: 2022-02-16 22:51
*/
public class Account implements Serializable {

private Integer id;
private Integer uid;
private Double money;

//多对一(mybatis中称之为一对一)的映射,一个账户只能属于一个用户 *
private User user;

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getUid() {
return uid;
}

public void setUid(Integer uid) {
this.uid = uid;
}

public Double getMoney() {
return money;
}

public void setMoney(Double money) {
this.money = money;
}

@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}

添加账户的持久层接口并使用注解配置

IAccountDao:

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
package com.keafmd.dao;

import com.keafmd.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* Keafmd
*
* @ClassName: IAccountDao
* @Description:
* @author: SerMs
* @date: 2021-02-16 22:54
*/

public interface IAccountDao {

/**
* 查询所有账户,并且获取每个账户下的用户信息,一对一
* @return
*/
@Select("select * from account")
@Results(id="accountMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "uid",property = "uid"),
@Result(column = "money",property = "money"),
@Result(property = "user",column = "uid",one=@One(select="com.keafmd.dao.IUserDao.findById",fetchType= FetchType.EAGER))
})
List<Account> findAll();
}

添加用户的持久层接口并使用注解配置

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
package com.keafmd.dao;

import com.keafmd.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* Keafmd
*
* @ClassName: IUserDao
* @Description:
* @author: SerMs
* @date: 2022-02-16 20:30
*/

/**
* 在mybatis中针对CRUD一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {

/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id = true,column = "id",property = "userId"),
@Result(column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday")

})
List<User> findAll();


/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id}")
//@ResultMap(value={"userMap"})
@ResultMap("userMap")
User findById(Integer userId);

/**
* 根据用户名称模糊查询
* @param username
* @return
*/
@Select("select * from user where username like #{username}") //占位符
@ResultMap("userMap")
List<User> findByName(String username);

}

测试一对一关联及立即加载

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
package com.keafmd.test;

import com.keafmd.dao.IAccountDao;
import com.keafmd.dao.IUserDao;
import com.keafmd.domain.Account;
import com.keafmd.domain.User;
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.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
* Keafmd
*
* @ClassName: AnnotationCRUDTest
* @Description: 注解开发CRUD测试
* @author: SerMs
* @date: 2022-02-16 21:05
*/
public class AccountTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IAccountDao accountDao;

@Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
accountDao = session.getMapper(IAccountDao.class);
}

@After
public void destory() throws Exception{
session.commit();
session.close();
in.close();
}

@Test
public void testFindAll(){
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println("-----每个账户信息-----");
System.out.println(account);
System.out.println(account.getUser());
}
}

}

运行结果:

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
2021-02-17 03:04:39,939 163    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2021-02-17 03:04:40,190 414 [ main] DEBUG source.pooled.PooledDataSource - Created connection 1176735295.
2021-02-17 03:04:40,190 414 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@46238e3f]
2021-02-17 03:04:40,195 419 [ main] DEBUG keafmd.dao.IAccountDao.findAll - ==> Preparing: select * from account
2021-02-17 03:04:40,226 450 [ main] DEBUG keafmd.dao.IAccountDao.findAll - ==> Parameters:
2021-02-17 03:04:40,267 491 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ====> Preparing: select * from user where id=?
2021-02-17 03:04:40,268 492 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ====> Parameters: 41(Integer)
2021-02-17 03:04:40,270 494 [ main] DEBUG m.keafmd.dao.IUserDao.findById - <==== Total: 1
2021-02-17 03:04:40,271 495 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ====> Preparing: select * from user where id=?
2021-02-17 03:04:40,271 495 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ====> Parameters: 45(Integer)
2021-02-17 03:04:40,272 496 [ main] DEBUG m.keafmd.dao.IUserDao.findById - <==== Total: 1
2021-02-17 03:04:40,273 497 [ main] DEBUG keafmd.dao.IAccountDao.findAll - <== Total: 3
-----每个账户信息-----
Account{id=1, uid=41, money=1000.0}
User{userId=41, userName='update user clear cache', userAddress='null', userSex='男', userBirthday=Tue Feb 27 17:47:08 CST 2018}
-----每个账户信息-----
Account{id=2, uid=45, money=1000.0}
User{userId=45, userName='新一', userAddress='null', userSex='男', userBirthday=Sun Mar 04 12:04:06 CST 2018}
-----每个账户信息-----
Account{id=3, uid=41, money=2000.0}
User{userId=41, userName='update user clear cache', userAddress='null', userSex='男', userBirthday=Tue Feb 27 17:47:08 CST 2018}
2021-02-17 03:04:40,274 498 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@46238e3f]
2021-02-17 03:04:40,274 498 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@46238e3f]
2021-02-17 03:04:40,274 498 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 1176735295 to pool.

Process finished with exit code 0

使用注解实现一对多复杂关系映射及延迟加载

需求:查询用户信息时,也要查询他的账户列表。使用注解方式实现。
分析:一个用户具有多个账户信息,所以形成了用户(User)与账户(Account)之间的一对多关系。

User 实体类加入 List<Account>

User:

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
package com.keafmd.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
* Keafmd
*
* @ClassName: User
* @Description: User实体类
* @author: SerMs
* @date: 2021-02-16 20:28
*/
public class User implements Serializable {
private Integer userId;
private String userName;
private String userAddress;
private String userSex;
private Date userBirthday;

//一对多关系映射:一个用户对应多个账户
private List<Account> accounts;

public List<Account> getAccounts() {
return accounts;
}

public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getUserAddress() {
return userAddress;
}

public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}

public String getUserSex() {
return userSex;
}

public void setUserSex(String userSex) {
this.userSex = userSex;
}

public Date getUserBirthday() {
return userBirthday;
}

public void setUserBirthday(Date userBirthday) {
this.userBirthday = userBirthday;
}

@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userAddress='" + userAddress + '\'' +
", userSex='" + userSex + '\'' +
", userBirthday=" + userBirthday +
'}';
}
}

编写用户的持久层接口并使用注解配置

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.keafmd.dao;

import com.keafmd.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* Keafmd
*
* @ClassName: IUserDao
* @Description:
* @author: SerMs
* @date: 2021-02-16 20:30
*/

/**
* 在mybatis中针对CRUD一共有四个注解
* @Select @Insert @Update @Delete
*/
public interface IUserDao {

/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id = true,column = "id",property = "userId"),
@Result(column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
@Result(property = "accounts" ,column = "id",
many = @Many(select = "com.keafmd.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))

})
List<User> findAll();


/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id}")
//@ResultMap(value={"userMap"})
@ResultMap("userMap")
User findById(Integer userId);

/**
* 根据用户名称模糊查询
* @param username
* @return
*/
@Select("select * from user where username like #{username}") //占位符
@ResultMap("userMap")
List<User> findByName(String username);
}

编写账户的持久层接口并使用注解配置

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
package com.keafmd.dao;

import com.keafmd.domain.Account;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* Keafmd
*
* @ClassName: IAccountDao
* @Description:
* @author: SerMs
* @date: 2021-02-16 22:54
*/

public interface IAccountDao {

/**
* 查询所有账户,并且获取每个账户下的用户信息,一对一 ,* 这里用不到这个findAll()
* @return
*/
@Select("select * from account")
@Results(id="accountMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "uid",property = "uid"),
@Result(column = "money",property = "money"),
@Result(property = "user",column = "uid",one=@One(select="com.keafmd.dao.IUserDao.findById",fetchType= FetchType.EAGER))
})
List<Account> findAll();


/**
* 根据用户id查询账户信息
* @param userId
* @return
*/
@Select("select * from account where uid = #{userId}")
List<Account> findAccountByUid(Integer userId);

}

编写测试代码

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
package com.keafmd.test;

import com.keafmd.dao.IUserDao;
import com.keafmd.domain.User;
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.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
* Keafmd
*
* @ClassName: AnnotationCRUDTest
* @Description: 注解开发CRUD测试
* @author: SerMs
* @date: 2021-02-16 21:05
*/
public class UserTest {
private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;

@Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class);
}

@After
public void destory() throws Exception{
session.commit();
session.close();
in.close();
}

@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for (User user : users) {
System.out.println("-----每个用户的信息");
System.out.println(user);
System.out.println(user.getAccounts());
}
}


}

运行 testFindAll()的结果:

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
2021-02-17 03:14:19,655 378    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2021-02-17 03:14:20,124 847 [ main] DEBUG source.pooled.PooledDataSource - Created connection 1176735295.
2021-02-17 03:14:20,124 847 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@46238e3f]
2021-02-17 03:14:20,135 858 [ main] DEBUG om.keafmd.dao.IUserDao.findAll - ==> Preparing: select * from user
2021-02-17 03:14:20,183 906 [ main] DEBUG om.keafmd.dao.IUserDao.findAll - ==> Parameters:
2021-02-17 03:14:20,471 1194 [ main] DEBUG om.keafmd.dao.IUserDao.findAll - <== Total: 9
-----每个用户的信息
2021-02-17 03:14:20,473 1196 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:14:20,474 1197 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 41(Integer)
2021-02-17 03:14:20,475 1198 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 2
User{userId=41, userName='update user clear cache', userAddress='null', userSex='男', userBirthday=Tue Feb 27 17:47:08 CST 2018}
[Account{id=1, uid=41, money=1000.0}, Account{id=3, uid=41, money=2000.0}]
-----每个用户的信息
2021-02-17 03:14:20,476 1199 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:14:20,476 1199 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 42(Integer)
2021-02-17 03:14:20,477 1200 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=42, userName='update', userAddress='null', userSex='男', userBirthday=Mon Feb 08 19:37:31 CST 2021}
[]
-----每个用户的信息
2021-02-17 03:14:20,479 1202 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:14:20,480 1203 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 43(Integer)
2021-02-17 03:14:20,481 1204 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=43, userName='小二王', userAddress='null', userSex='女', userBirthday=Sun Mar 04 11:34:34 CST 2018}
[]
-----每个用户的信息
2021-02-17 03:14:20,481 1204 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:14:20,482 1205 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 45(Integer)
2021-02-17 03:14:20,483 1206 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 1
User{userId=45, userName='新一', userAddress='null', userSex='男', userBirthday=Sun Mar 04 12:04:06 CST 2018}
[Account{id=2, uid=45, money=1000.0}]
-----每个用户的信息
2021-02-17 03:14:20,484 1207 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:14:20,484 1207 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 50(Integer)
2021-02-17 03:14:20,484 1207 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=50, userName='Keafmd', userAddress='null', userSex='男', userBirthday=Mon Feb 08 15:44:01 CST 2021}
[]
-----每个用户的信息
2021-02-17 03:14:20,485 1208 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:14:20,485 1208 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 51(Integer)
2021-02-17 03:14:20,486 1209 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=51, userName='update DAO', userAddress='null', userSex='男', userBirthday=Tue Feb 09 11:31:38 CST 2021}
[]
-----每个用户的信息
2021-02-17 03:14:20,488 1211 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:14:20,489 1212 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 52(Integer)
2021-02-17 03:14:20,491 1214 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=52, userName='Keafmd DAO', userAddress='null', userSex='男', userBirthday=Tue Feb 09 11:29:41 CST 2021}
[]
-----每个用户的信息
2021-02-17 03:14:20,491 1214 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:14:20,492 1215 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 53(Integer)
2021-02-17 03:14:20,493 1216 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=53, userName='Keafmd laset insertid 1', userAddress='null', userSex='男', userBirthday=Fri Feb 12 20:53:46 CST 2021}
[]
-----每个用户的信息
2021-02-17 03:14:20,493 1216 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:14:20,493 1216 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 55(Integer)
2021-02-17 03:14:20,494 1217 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=55, userName='mybatis annotation', userAddress='null', userSex='男', userBirthday=Tue Feb 16 22:15:36 CST 2021}
[]
2021-02-17 03:14:20,495 1218 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@46238e3f]
2021-02-17 03:14:20,495 1218 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@46238e3f]
2021-02-17 03:14:20,495 1218 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 1176735295 to pool.

Process finished with exit code 0

可以看出来延迟加载,在每次加载每个用户时都会查询一次。

修改测试代码:

1
2
3
4
5
6
7
8
9
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
/*for (User user : users) {
System.out.println("-----每个用户的信息");
System.out.println(user);
System.out.println(user.getAccounts());
}*/
}

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
2021-02-17 03:17:26,203 166    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2021-02-17 03:17:26,500 463 [ main] DEBUG source.pooled.PooledDataSource - Created connection 1176735295.
2021-02-17 03:17:26,500 463 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@46238e3f]
2021-02-17 03:17:26,505 468 [ main] DEBUG om.keafmd.dao.IUserDao.findAll - ==> Preparing: select * from user
2021-02-17 03:17:26,540 503 [ main] DEBUG om.keafmd.dao.IUserDao.findAll - ==> Parameters:
2021-02-17 03:17:26,613 576 [ main] DEBUG om.keafmd.dao.IUserDao.findAll - <== Total: 9
2021-02-17 03:17:26,614 577 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@46238e3f]
2021-02-17 03:17:26,614 577 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@46238e3f]
2021-02-17 03:17:26,614 577 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 1176735295 to pool.

Process finished with exit code 0

这样通过对比就可以很明显的看出来延迟加载的效果。

回顾下一级缓存

运行代码:

1
2
3
4
5
6
7
8
9
10
11
@Test
public void testFindOne(){
User user = userDao.findById(55);
System.out.println(user);

User user2 = userDao.findById(55);
System.out.println(user2);

System.out.println(user==user2);
}

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2021-02-17 03:26:22,736 164    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2021-02-17 03:26:22,970 398 [ main] DEBUG source.pooled.PooledDataSource - Created connection 85445963.
2021-02-17 03:26:22,971 399 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:26:22,975 403 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Preparing: select * from user where id=?
2021-02-17 03:26:23,001 429 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Parameters: 55(Integer)
2021-02-17 03:26:23,054 482 [ main] DEBUG m.keafmd.dao.IUserDao.findById - <== Total: 1
2021-02-17 03:26:23,055 483 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:26:23,055 483 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 55(Integer)
2021-02-17 03:26:23,056 484 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=55, userName='mybatis annotation', userAddress='null', userSex='男', userBirthday=Tue Feb 16 22:15:36 CST 2021}
User{userId=55, userName='mybatis annotation', userAddress='null', userSex='男', userBirthday=Tue Feb 16 22:15:36 CST 2021}
true
2021-02-17 03:26:23,056 484 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:26:23,056 484 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:26:23,057 485 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 85445963 to pool.

mybatis 基于注解的二级缓存

在 SqlMapConfig.xml 中开启二级缓存支持

1
2
3
4
<!--配置开启二级缓存-->
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>

在持久层接口中使用注解配置二级缓存

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
package com.keafmd.dao;

import com.keafmd.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
* Keafmd
*
* @ClassName: IUserDao
* @Description:
* @author: SerMs
* @date: 2021-02-16 20:30
*/

/**
* 在mybatis中针对CRUD一共有四个注解
* @Select @Insert @Update @Delete
*/
@CacheNamespace(blocking = true) //mybatis 基于注解方式实现配置二级缓存 *这里*
public interface IUserDao {

/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@Results(id="userMap",value={
@Result(id = true,column = "id",property = "userId"),
@Result(column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
@Result(property = "accounts" ,column = "id",
many = @Many(select = "com.keafmd.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))

})
List<User> findAll();


/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id}")
//@ResultMap(value={"userMap"})
@ResultMap("userMap")
User findById(Integer userId);

/**
* 根据用户名称模糊查询
* @param username
* @return
*/
@Select("select * from user where username like #{username}") //占位符
@ResultMap("userMap")
List<User> findByName(String username);


}

编写测试二级缓存的测试类

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
package com.keafmd.test;

import com.keafmd.dao.IUserDao;
import com.keafmd.domain.User;
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.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

/**
* Keafmd
*
* @ClassName: SecondLevelCatchTest
* @Description: 二级缓存测试
* @author: SerMs
* @date: 2022-02-16 23:37
*/
public class SecondLevelCatchTest {
private InputStream in;
private SqlSessionFactory factory;

@Before
public void init() throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
}

@After
public void destory() throws Exception{


in.close();
}


@Test
public void testFindOne(){
SqlSession session = factory.openSession();
IUserDao userDao = session.getMapper(IUserDao.class);
User user = userDao.findById(55);
System.out.println(user);

session.close();//释放一级缓存

SqlSession session1 = factory.openSession();//再次打开session
IUserDao userDao1 = session1.getMapper(IUserDao.class);

User user2 = userDao1.findById(55);
System.out.println(user2);

System.out.println(user==user2);
}


}

不开启二级缓存配置的运行结果:

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
2021-02-17 03:31:32,119 320    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2021-02-17 03:31:32,509 710 [ main] DEBUG source.pooled.PooledDataSource - Created connection 85445963.
2021-02-17 03:31:32,510 711 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:31:32,514 715 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Preparing: select * from user where id=?
2021-02-17 03:31:32,551 752 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Parameters: 55(Integer)
2021-02-17 03:31:32,633 834 [ main] DEBUG m.keafmd.dao.IUserDao.findById - <== Total: 1
2021-02-17 03:31:32,634 835 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:31:32,634 835 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 55(Integer)
2021-02-17 03:31:32,635 836 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=55, userName='mybatis annotation', userAddress='null', userSex='男', userBirthday=Tue Feb 16 22:15:36 CST 2021}
2021-02-17 03:31:32,635 836 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:31:32,636 837 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:31:32,636 837 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 85445963 to pool.
2021-02-17 03:31:32,636 837 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Opening JDBC Connection
2021-02-17 03:31:32,636 837 [ main] DEBUG source.pooled.PooledDataSource - Checked out connection 85445963 from pool.
2021-02-17 03:31:32,636 837 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@517cd4b]
2021-02-17 03:31:32,636 837 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Preparing: select * from user where id=?
2021-02-17 03:31:32,637 838 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Parameters: 55(Integer)
2021-02-17 03:31:32,639 840 [ main] DEBUG m.keafmd.dao.IUserDao.findById - <== Total: 1
2021-02-17 03:31:32,641 842 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:31:32,641 842 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 55(Integer)
2021-02-17 03:31:32,642 843 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=55, userName='mybatis annotation', userAddress='null', userSex='男', userBirthday=Tue Feb 16 22:15:36 CST 2021}
false

Process finished with exit code 0

开启二级缓存配置的运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2021-02-17 03:29:23,197 373    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2021-02-17 03:29:23,605 781 [ main] DEBUG source.pooled.PooledDataSource - Created connection 500179317.
2021-02-17 03:29:23,606 782 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1dd02175]
2021-02-17 03:29:23,617 793 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Preparing: select * from user where id=?
2021-02-17 03:29:23,668 844 [ main] DEBUG m.keafmd.dao.IUserDao.findById - ==> Parameters: 55(Integer)
2021-02-17 03:29:23,777 953 [ main] DEBUG m.keafmd.dao.IUserDao.findById - <== Total: 1
2021-02-17 03:29:23,781 957 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Preparing: select * from account where uid = ?
2021-02-17 03:29:23,782 958 [ main] DEBUG o.IAccountDao.findAccountByUid - ==> Parameters: 55(Integer)
2021-02-17 03:29:23,782 958 [ main] DEBUG o.IAccountDao.findAccountByUid - <== Total: 0
User{userId=55, userName='mybatis annotation', userAddress='null', userSex='男', userBirthday=Tue Feb 16 22:15:36 CST 2021}
2021-02-17 03:29:23,790 966 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1dd02175]
2021-02-17 03:29:23,791 967 [ main] DEBUG ansaction.jdbc.JdbcTransaction - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1dd02175]
2021-02-17 03:29:23,791 967 [ main] DEBUG source.pooled.PooledDataSource - Returned connection 500179317 to pool.
2021-02-17 03:29:23,800 976 [ main] DEBUG com.keafmd.dao.IUserDao - Cache Hit Ratio [com.keafmd.dao.IUserDao]: 0.5
User{userId=55, userName='mybatis annotation', userAddress='null', userSex='男', userBirthday=Tue Feb 16 22:15:36 CST 2021}
false

Process finished with exit code 0

效果很明显,开启使用二级缓存时第二次并没有发起查询,证明使用的就是二级缓存。

以上就是 Mybatis 注解开发(超详细)的全部内容。

看完如果对你有帮助,感谢赞助支持!