Mybatis-03

Mybatis-03

14、动态SQL语句

动态的sql语句是指,mysql通过配置,根据不同的参数值,生成不同的sql语句.

准备工作:

1
2
3
4
5
public class User {
private int id;
private String lastName;
private int sex;
}

14.1、if 语句

说明: if语句,可以动态的根据你的值来决定,是否需要动态的修改查询条件,最终产生不同的sql语句.

Mapper接口:

1
2
3
4
5
6
7
8
public interface UserMapper {
/**
* 查询跟user的lastName有关的用户,或跟user性别相同的用户<br/>
* 拿 user 的lastName属性做模糊查询,做user的sex查询用户
*/
public List<User> queryUsersBySample(User user);

}

Mapper.xml配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!--    /**
* 查询跟user的lastName有关的用户,或跟user性别相同的用户<br/>
* 拿 user 的lastName属性做模糊查询,做user的sex查询用户
*/
public List<User> queryUsersBySample(User user);-->
<select id="queryUsersBySample" parameterType="com.atguigu.pojo.User"
resultType="com.atguigu.pojo.User">
select
`id`,`last_name` lastName,`sex`
from
t_user
where
<!-- if标签做if判断 -->
<if test="lastName != null">
last_name like concat('%',#{lastName},'%')
</if>
<if test="sex == 0 || sex == 1">
or
sex = #{sex}
</if>
</select>

测试代码:

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
public class UserMapperTest {

static SqlSessionFactory sqlSessionFactory;

@Before
public void init() throws IOException {
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsStream("mybatis-config.xml"));
}

@Test
public void queryUsersBySample() {

SqlSession session = sqlSessionFactory.openSession();

try {
UserMapper mapper = session.getMapper(UserMapper.class);

mapper.queryUsersBySample(new User(null,"b",10)).forEach(System.out::println);

} finally {
session.close();
}
}
}

14.2、where 语句

说明: where语句,可以帮我们在多个动态语句中,有效的去掉前面的多余的and 或 or 之类的多余关键字

where语句还可以根据包含的内容是否有值, 有内容就添加where关键字.没内容不添加where关键字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!--    /**
* 查询跟user的lastName有关的用户,或跟user性别相同的用户<br/>
* 拿 user 的lastName属性做模糊查询,做user的sex查询用户
*/
public List<User> queryUsersBySample(User user);-->
<select id="queryUsersBySample" parameterType="com.atguigu.pojo.User"
resultType="com.atguigu.pojo.User">
select
`id`,`last_name` lastName,`sex`
from
t_user
<where>
<!-- if标签做if判断 -->
<if test="lastName != null">
last_name like concat('%',#{lastName},'%')
</if>
<if test="sex == 0 || sex == 1">
or
sex = #{sex}
</if>
</where>
</select>

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void queryUsersBySample() {

SqlSession session = sqlSessionFactory.openSession();

try {
UserMapper mapper = session.getMapper(UserMapper.class);

mapper.queryUsersBySample(new User(null,null,10)).forEach(System.out::println);

} finally {
session.close();
}
}

14.3、trim语句

说明: trim 可以动态在包含的语句前面和后面添加内容。也可以去掉前面或者后面给定的内容

prefix 前面添加内容

​ suffix 后面添加内容

​ suffixOverrides 去掉的后面内容

​ prefixOverrides 去掉的前面内容

mapper.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
<!--    /**
* 查询跟user的lastName有关的用户,或跟user性别相同的用户<br/>
* 拿 user 的lastName属性做模糊查询,做user的sex查询用户
*/
public List<User> queryUsersBySample(User user);-->
<select id="queryUsersBySample" parameterType="com.atguigu.pojo.User"
resultType="com.atguigu.pojo.User">
select
`id`,`last_name` lastName,`sex`
from
t_user
<!--
prefix 前面添加内容
suffix 后面添加内容
suffixOverrides 去掉的后面内容
prefixOverrides 去掉的前面内容
-->
<trim suffixOverrides="or" prefix="where">
<!-- if标签做if判断 -->
<if test="lastName != null">
last_name like concat('%',#{lastName},'%')
or
</if>
<if test="sex == 0 || sex == 1">
sex = #{sex}
</if>
</trim>
</select>

测试的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void queryUsersBySample() {

SqlSession session = sqlSessionFactory.openSession();

try {
UserMapper mapper = session.getMapper(UserMapper.class);

mapper.queryUsersBySample(new User(null,"b",10)).forEach(System.out::println);

} finally {
session.close();
}
}

14.4、choose( when , otherwise )语句

说明:choose when otherwise 可以执行多路选择判断,但是只会有一个分支会被执行。

类似switch case 语句

Mapper接口:

1
2
3
4
5
6
/**
* 如果lastName值有效,则只用lastName模糊查询 <br>
* 如果lastName值无效,而sex值有效,则只使用sex查询 <br/>
* 如果都无效,则可以使用自定义查询条件
*/
public List<User> queryUsersBySampleChoose(User user);

Mapper.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
<!--    /**
* 如果lastName值有效,则只用lastName模糊查询 <br>
* 如果lastName值无效,而sex值有效,则只使用sex查询 <br/>
* 如果都无效,则可以使用自定义查询条件
*/
public List<User> queryUsersBySampleChoose(User user);-->
<select id="queryUsersBySampleChoose" parameterType="com.atguigu.pojo.User"
resultType="com.atguigu.pojo.User">
select
`id`,`last_name` lastName,`sex`
from
t_user
<where>
<choose>
<when test="lastName != null">
last_name like concat('%',#{lastName},'%')
</when>
<when test="sex == 0 || sex == 1">
sex = #{sex}
</when>
<otherwise>
id = 6
</otherwise>
</choose>
</where>
</select>

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void queryUsersBySampleChoose() {

SqlSession session = sqlSessionFactory.openSession();

try {
UserMapper mapper = session.getMapper(UserMapper.class);

mapper.queryUsersBySampleChoose(new User(null,null,10)).forEach(System.out::println);

} finally {
session.close();
}
}

14.5、set语句

set语句可以删除set关键字 条件前后的 逗号

Mapper接口:

1
2
3
4
5
6
/**
* 更新
* @param user
* @return
*/
public int updateUser(User user);

mapper.xml配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!--    /**
* 更新
* @param user
* @return
*/
public int updateUser(User user);-->
<update id="updateUser" parameterType="com.atguigu.pojo.User">
update
t_user
<set>
<if test="lastName != null">
`last_name` = #{lastName}
</if>
<if test="sex == 0 || sex == 1">
, `sex` = #{sex}
</if>
</set>
<where>
id = #{id}
</where>
</update>

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
public void updateUser() {

SqlSession session = sqlSessionFactory.openSession();

try {
UserMapper mapper = session.getMapper(UserMapper.class);

mapper.updateUser(new User(6,null,1 ));

session.commit();
} finally {
session.close();
}
}

14.6、foreach语句

foreach语句可以做遍历.经常用于以下两种情况的sql语句生成

select * from 表名 where id in( xx ,xx ,xx );

Mapper接口:

1
2
//    select * from 表名 where id in( xx ,xx ,xx );
public List<User> queryUsersByIds(List<Integer> ids );

Mapper.xml配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<select id="queryUsersByIds" resultType="com.atguigu.pojo.User">
select
`id`,`last_name` lastName,`sex`
from
t_user
where
id in
<!--
foreach标签用来做遍历操作
collection 是遍历的数据源( 参数名 )
item 当前遍历到的数据
separator 两个元素之间的分隔符
open="(" 遍历开始的内容
close=")" 遍历结束的内容
-->
<foreach collection="list" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</select>

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
public void queryUsersByIds() {
SqlSession session = sqlSessionFactory.openSession();

try {
UserMapper mapper = session.getMapper(UserMapper.class);

List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);

for (User queryUsersById : mapper.queryUsersByIds(ids)) {
System.out.println(queryUsersById);
}
} finally {
session.close();
}
}

insert into 表名(列名,列名) values(值1,值2),(值1,值2),(值1,值2)

Mapper接口:

1
2
//    insert into 表名(列名,列名) values(值1,值2),(值1,值2),(值1,值2)
public int insertUsers(List<User> users);

Mapper.xml配置文件:

1
2
3
4
5
6
7
8
<!--    public int insertUsers(List<User> users);-->
<insert id="insertUsers" >
insert into t_user(`last_name`,`sex`)
values
<foreach collection="list" item="user" separator=",">
(#{user.lastName},#{user.sex})
</foreach>
</insert>

测试的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Test
public void insertUsers() {
SqlSession session = sqlSessionFactory.openSession();

try {
UserMapper mapper = session.getMapper(UserMapper.class);

List<User> userList = new ArrayList<>();

userList.add(new User(null,"aaa", 0));
userList.add(new User(null,"bbb", 1));
userList.add(new User(null,"ccc", 0));

mapper.insertUsers(userList);

session.commit();
} finally {
session.close();
}
}

14.7、sql片段

是指将多个sql语句中公共部分的内容进行抽取.然后在每个sql语句是进行引入( 包含 ). 这样的好处,就是可以统一维护一分

15、mybatis缓存

缓存: 指的是把经常访问的数据保存到一个高速的缓冲区中.方便后面访问的时候可以快速的获取到这些数据.

名词,缓存是指被保存在高速缓冲区中的数据,也叫缓存

缓存只有一个目标,就是为了提高访问速度.

一级缓存: 同一个SqlSession对象

二级缓存: 同一个SqlSessionFactory对象.

15.1、mybatis的一级缓存的示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
@Test
public void queryUserById() throws InterruptedException {

SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

System.out.println(mapper.queryUserById(1));

System.out.println(mapper.queryUserById(1));

} finally {
sqlSession.close();
}

}

15.1.2、一级缓存的管理

缓存失效的四种情况:

1.不在同一个SqlSession对象中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void queryOne(){
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

System.out.println(mapper.queryUserById(1));

} finally {
sqlSession.close();
}
}

/**
* 1.不在同一个SqlSession对象中
*/
@Test
public void firstCacheFail1() {
queryOne();
queryOne();
}

2.执行语句的参数不同。缓存中也不存在数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void firstCacheFail2() throws InterruptedException {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

System.out.println(mapper.queryUserById(1));

System.out.println(mapper.queryUserById(2));

} finally {
sqlSession.close();
}
}

3.手动清空缓存数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void firstCacheFail3() throws InterruptedException {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

System.out.println(mapper.queryUserById(1));
sqlSession.clearCache();// 清空缓存
System.out.println(mapper.queryUserById(1));

} finally {
sqlSession.close();
}
}

4.执行增,删,改,语句,会清空掉缓存

Mapper接口:

1
2
3
4
5
6
7
public interface UserMapper {

public User queryUserById(Integer id);

public int insertUser(User user);

}

mapper.xml配置文件:

1
2
3
4
5
6
7
8
<!--    public User queryUserById(Integer id);-->
<select id="queryUserById" resultType="com.atguigu.pojo.User">
select `id`,`last_name` lastName,`sex` from t_user where id = #{id}
</select>
<!-- public int insertUser(User user);-->
<insert id="insertUser" parameterType="com.atguigu.pojo.User">
insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex})
</insert>

测试的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
public void firstCacheFail4() throws InterruptedException {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

System.out.println(mapper.queryUserById(1));

mapper.insertUser(new User(null,"asdf", 1));

System.out.println(mapper.queryUserById(1));

sqlSession.commit();
} finally {
sqlSession.close();
}
}

15.2、mybatis的二级缓存

二级缓存的图解示意

二级缓存的使用:

1、mybatis二级缓存默认不开启,需要到mybatis-config.xml配置文件中,通过settings配置启动

2、在Mapper.xml的配置文件中加入cache标签表示使用二级缓存。

3、需要被二级缓存的对象必须要实现java的序列化接口。

15.2.1、二级缓存的演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void queryOne(){
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

System.out.println(mapper.queryUserById(1));

} finally {
sqlSession.close();
}
}

/**
*
*/
@Test
public void secondCache() {
queryOne();
queryOne();
}

15.2.2、useCache=“false“**的演示和说明

在select标签上有一个useCache标签,表示是否使用二级缓存。默认值是true,表示使用。

1
2
3
4
5
6
<!--    
useCache="false" 表示不把查询的结果放到二级缓存中
-->
<select id="queryUserById" resultType="com.atguigu.pojo.User" useCache="false">
select `id`,`last_name` lastName,`sex` from t_user where id = #{id}
</select>

15.2.3、flushCache=“false“**的演示和说明

在update,delete,insert标签上,都有flushCache属性。表示是否清空缓存。默认是默认是true表示清空缓存。如果是false表示不清空缓存。

自定义二级缓存( 了解 )

一级缓存的默认实现类: org.apache.ibatis.cache.impl.PerpetualCache类

1、需要我们编写一个类去实现一个接口Cache.

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
public class MySecondCache implements Cache {

private final String id;
private Map<Object, Object> cache = new HashMap();

public MySecondCache(String id) {
this.id = id;
}

public String getId() {
return this.id;
}

public int getSize() {
return this.cache.size();
}

public void putObject(Object key, Object value) {
System.out.println(" 自定义 二级缓存 保存数据 putObject ");
this.cache.put(key, value);
}

public Object getObject(Object key) {
System.out.println(" 自定义 二级缓存 获取数据 getObject ");
return this.cache.get(key);
}

public Object removeObject(Object key) {
return this.cache.remove(key);
}

public void clear() {
this.cache.clear();
}

public ReadWriteLock getReadWriteLock() {
return null;
}

public boolean equals(Object o) {
if (this.getId() == null) {
throw new CacheException("Cache instances require an ID.");
} else if (this == o) {
return true;
} else if (!(o instanceof Cache)) {
return false;
} else {
Cache otherCache = (Cache)o;
return this.getId().equals(otherCache.getId());
}
}

public int hashCode() {
if (this.getId() == null) {
throw new CacheException("Cache instances require an ID.");
} else {
return this.getId().hashCode();
}
}
}

2、到mapper.xml配置文件中的cache标签里设置type属性的值

16、缓存的使用顺序说明:

1 当mybatis执行一个查询的时候,会先去二级缓存中查询数据。有就直接返回。

2 如果二级缓存中没有数据,再到一级缓存中获取,有就直接返回

3 如果二级,一级都没有要查的数据,则发sql语句到数据库查询

4 查到结果后会马上放到一级缓存中

5 当SqlSession关闭的时候,会把一级缓存中的数据同步到二级缓存中

17、mybatis 逆向工程

MyBatis逆向工程,简称MBG。是一个专门为MyBatis框架使用者定制的代码生成器。可以快速的根据表生成对应的映射文件,接口,以及Bean类对象。

在Mybatis中,有一个可以自动对单表生成的增,删,改,查代码的插件。

叫 mybatis-generator-core-1.3.2。

它可以帮我们对比数据库表之后,生成大量的这个基础代码。

这些基础代码有:

1、数据库表对应的javaBean对象

2、这些javaBean对象对应的Mapper接口

3、这些Mapper接口对应的配置文件

1
2
3
4
5
<!-- 去掉全部的注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>

17.1、准备数据库表

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

create database mbg;

use mbg;

create table t_user(
`id` int primary key auto_increment,
`username` varchar(30) not null unique,
`password` varchar(40) not null,
`email` varchar(50)
);

insert into t_user(`username`,`password`,`email`) values('admin','admin','admin@atguigu.com');
insert into t_user(`username`,`password`,`email`) values('wzg168','123456','admin@atguigu.com');
insert into t_user(`username`,`password`,`email`) values('admin168','123456','admin@atguigu.com');
insert into t_user(`username`,`password`,`email`) values('lisi','123456','admin@atguigu.com');
insert into t_user(`username`,`password`,`email`) values('wangwu','123456','admin@atguigu.com');

create table t_book(
`id` int primary key auto_increment,
`name` varchar(50),
`author` varchar(50),
`price` decimal(11,2),
`sales` int,
`stock` int
);


## 插入初始化测试数据
insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , 'java从入门到放弃' , '国哥' , 80 , 9999 , 9);

insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '数据结构与算法' , '严敏君' , 78.5 , 6 , 13);

insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '怎样拐跑别人的媳妇' , '龙伍' , 68, 99999 , 52);

insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '木虚肉盖饭' , '小胖' , 16, 1000 , 50);

insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , 'C++编程思想' , '刚哥' , 45.5 , 14 , 95);

insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '蛋炒饭' , '周星星' , 9.9, 12 , 53);

insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock` )
values(null , '赌神' , '龙伍' , 66.5, 125 , 535);

select * from t_user;
select * from t_book;

mbg.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>

<!--
targetRuntime 可以设置生成的版本
MyBatis3 豪华版本
MyBatis3Simple CRUD操作
-->
<context id="DB2Tables" targetRuntime="MyBatis3">

<!-- 去掉全部的注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>

<!--
修改数据库的四个连接属性
-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mbg"
userId="root"
password="root">
</jdbcConnection>

<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>

<!--
javaModelGenerator生成javaBean
targetPackage指定生成的包
targetProject指定生成的项目位置
-->
<javaModelGenerator targetPackage="com.atguigu.pojo"
targetProject=".\mybatis_mbg\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>

<!--
sqlMapGenerator标签是生成mapper.xml配置信息
targetPackage指定生成的包
targetProject指定生成的项目位置
-->
<sqlMapGenerator targetPackage="com.atguigu.mapper"
targetProject=".\mybatis_mbg\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>

<!--
javaClientGenerator生成mapper接口
targetPackage指定生成的包
targetProject指定生成的项目位置
-->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.atguigu.mapper"
targetProject=".\mybatis_mbg\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>

<!--
table标签,一个标签一个数据库表
tableName是表名
domainObjectName生成的类名
-->
<table tableName="t_user" domainObjectName="User" ></table>
<table tableName="t_book" domainObjectName="Book" ></table>

</context>
</generatorConfiguration>

mybatis逆向工程运行代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.mybatis.mbg;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Runner {

public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mybatis_mbg/mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}

测试的代码:

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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package com.atguigu.mapper.test;

import com.atguigu.mapper.BookMapper;
import com.atguigu.pojo.Book;
import com.atguigu.pojo.BookExample;
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 java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import static org.junit.Assert.*;

public class BookMapperTest {

static SqlSessionFactory sqlSessionFactory;


@Before
public void init() throws IOException {
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsStream("mybatis-config.xml"));
}

@Test
public void countByExample() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

// countByExample();//用于求记录数 count() 用于做统计个数
// 求50块以上的图书个数
BookExample bookExample = new BookExample();
// 创建一个条件对象
BookExample.Criteria criteria = bookExample.createCriteria();
// 条件大于50的价格 并且 销量大于100
criteria.andPriceGreaterThan(new BigDecimal(50));
criteria.andSalesGreaterThanOrEqualTo(100);
criteria.andNameLike("%入%");
int i = mapper.countByExample(bookExample);

System.out.println(i);

session.commit();
} finally {
session.close();
}
}

@Test
public void deleteByExample() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

// deleteByExample()按条件删除
BookExample bookExample = new BookExample();

// 删除书名是"赌神" 或 or 作者是"周星星" 的图书
BookExample.Criteria criteria = bookExample.createCriteria();
criteria.andNameEqualTo("赌神");
//创建一个or的条件
BookExample.Criteria or = bookExample.or();
or.andAuthorEqualTo("周星星");

int i = mapper.deleteByExample(bookExample);
System.out.println( i );
session.commit();
} finally {
session.close();
}
}

@Test
public void deleteByPrimaryKey() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

int i = mapper.deleteByPrimaryKey(5);

System.out.println(i);

session.commit();
} finally {
session.close();
}
}

@Test
public void insert() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);


int insert = mapper.insert(new Book(null, null, null, new BigDecimal(100), 0, 99999));
System.out.println(insert);

session.commit();
} finally {
session.close();
}
}

@Test
public void insertSelective() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

// insertSelective() 只会插入有值的列
int insert = mapper.insertSelective(new Book(null, null, null, new BigDecimal(100), 0, 99999));
System.out.println(insert);

session.commit();
} finally {
session.close();
}
}

@Test
public void selectByExample() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

// selectByExample()根据条件查询
BookExample bookExample = new BookExample();
// 作者等于"国哥" or 书名是 "怎样拐跑别人的媳妇"

BookExample.Criteria criteria = bookExample.createCriteria();
criteria.andAuthorEqualTo("国哥");
BookExample.Criteria or = bookExample.or();
or.andNameEqualTo("怎样拐跑别人的媳妇");

List<Book> books = mapper.selectByExample(bookExample);
books.forEach(System.out::println);

session.commit();
} finally {
session.close();
}
}

@Test
public void selectByPrimaryKey() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

// selectByPrimaryKey()根据主键来查询记录

System.out.println(mapper.selectByPrimaryKey(1));

session.commit();
} finally {
session.close();
}
}

@Test
public void updateByExampleSelective() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

BookExample bookExample = new BookExample();
// 书名等于 "木虚肉盖饭" 或 书名为null的
BookExample.Criteria criteria = bookExample.createCriteria();
criteria.andNameEqualTo("木虚肉盖饭");
BookExample.Criteria or = bookExample.or();
or.andNameIsNull();

// updateByExampleSelective() 根据条件更新非空的字段|列
int i = mapper.updateByExampleSelective(new Book(null,null,"aabb",new BigDecimal(100),1000,0), bookExample);
System.out.println(i);

session.commit();
} finally {
session.close();
}
}

@Test
public void updateByExample() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

// updateByExampleSelective() 根据条件更新, 非空的字段|列
// updateByExample() 根据条件更新

BookExample bookExample = new BookExample();
// 书名等于 "木虚肉盖饭" 或 书名为null的
BookExample.Criteria criteria = bookExample.createCriteria();
criteria.andNameEqualTo("木虚肉盖饭");
BookExample.Criteria or = bookExample.or();
or.andNameIsNull();

// updateByExampleSelective() 根据条件更新非空的字段|列
int i = mapper.updateByExample(new Book(null,null,"aabb",new BigDecimal(100),1000,0), bookExample);
System.out.println(i);

session.commit();
} finally {
session.close();
}
}

@Test
public void updateByPrimaryKeySelective() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

// updateByPrimaryKeySelective() 根据主键进行更新, 忽略空的字段|列

int count = mapper.updateByPrimaryKeySelective(new Book(10, "国哥好帅", null, new BigDecimal(100), 999, 0));
System.out.println(count);

session.commit();
} finally {
session.close();
}
}

@Test
public void updateByPrimaryKey() {
SqlSession session = sqlSessionFactory.openSession();
try {
BookMapper mapper = session.getMapper(BookMapper.class);

// 根据主键进行更新
int count = mapper.updateByPrimaryKey(new Book(10, "国哥好帅", null, new BigDecimal(100), 999, 0));
System.out.println(count);


session.commit();
} finally {
session.close();
}
}
}

Mybatis-03
http://www.kju147.com/2021/07/24/Mybatis-03/
作者
个人学习
发布于
2021年7月24日
许可协议