mybatis cheat sheet

-


maven 依赖

1
2
3
4
5
6
7
8
9
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>

配置

1
2
3
4
5
6
7
8
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/test

mybatis:
mapperLocations: classpath:mapper/**/*.xml

基本用法

1
2
3
4
5
6
@Mapper
public interface TestMapper {

// @Select("select * from todo limit 2")
List<Map<String,Object>> findTodos();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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="com.justdoit.springboottest.mapper.TestMapper">
<!-- 开启基于redis的二级缓存 -->
<!-- <cache type="com.justdoit.springboottest.config.MybatisCacheConfig" /> -->


<select id="findTodos" resultType="java.util.Map">
SELECT
*
FROM
todo
limit 3
</select>
</mapper>

最佳实践

多个参数

1
2
@Update("update role set role_name = #{role.roleName}, role_name_zh = #{role.roleNameZh} where id = #{id}")
public void update(int id, RoleParam role);

分页

PageHelper
  • 依赖
  • 配置
  • startPage
  • pageInfo
1
2
3
4
5
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
// 第几页
int currentPage = 2;
// 每页数量
int pageSize = 5;
// 排序
String orderBy = "id desc";
PageHelper.startPage(currentPage, pageSize, orderBy);
List<Map<String, Object>> todos = testMapper.findTodos();
PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(todos);
log.info(pageInfo.toString());

return todos;

like 模糊查询

  • 在代码中加上%
1
List<User> test = userMapper.findUserByLikeName2("%" +name+"%");
1
2
3
<select id="findUserByLikeName2" parameterType="java.lang.String" resultMap="user">
select * from t_user where name like #{name,jdbcType=VARCHAR}
</select>

动态 SQL

if

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<select id="findActiveBlogWithTitleLike" resultType="Blog">
SELECT
*
FROM
BLOG
WHERE
state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>

choose、when、otherwise

从多个条件中选择一个使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>

where

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>

set

1
2
3
4
5
6
7
8
9
10
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>

foreach

  • item:集合中元素迭代时的别名,该参数为必选。
  • index:在 list 和数组中,index 是元素的序号,在 map 中,index 是元素的 key,该参数可选
  • open:foreach 代码的开始符号,一般是(和 close=”)”合用。常用在 in(),values()时。该参数可选
  • separator:元素之间的分隔符,例如在 in()的时候,separator=”,”会自动在元素中间用“,“隔开,避免手动输入逗号导致 sql 错误,如 in(1,2,)这样。该参数可选。
  • close: foreach 代码的关闭符号,一般是)和 open=”(“合用。常用在 in(),values()时。该参数可选。
  • collection: 要做 foreach 的对象,作为入参时,List 对象默认用”list”代替作为键,数组对象有”array”代替作为键,Map 对象没有默认的键。当然在作为入参时可以使用@Param(“keyName”)来设置键,设置 keyName 后,list,array 将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:如果 User 有属性 List ids。入参是 User 对象,那么这个 collection = “ids”.如果 User 有属性 Ids ids;其中 Ids 是个对象,Ids 有个属性 List id;入参是 User 对象,那么 collection = “ids.id”

如果传入的是单参数且参数类型是一个 List 的时候,collection 属性值为 list .
如果传入的是单参数且参数类型是一个 array 数组的时候,collection 的属性值为 array .
如果传入的参数是多个的时候,我们就需要把它们封装成一个 Map 了,当然单参数也可以封装成 map,实际上如果你在传入参数的时候,在 MyBatis 里面也是会把它封装成一个 Map 的,map 的 key 就是参数名,所以这个时候 collection 属性值就是传入的 List 或 array 对象在自己封装的 map 里面的 key.

1
2
3
4
5
6
7
8
9
10
<select id="insertWeeklyCost" parameterType="java.util.List">
insert into weekly_cost(game_id,date,epiboly_cost,publicity_cost)
values
<foreach collection="list" item="element" index="index" open="(" separator="),(" close=")">
#{element.gameId},
#{element.date},
#{element.epiboly_cost},
#{element.publicity_cost}
</foreach>
</select>

一级缓存


二级缓存

1
<cache type="com.justdoit.springboottest.config.MybatisCacheConfig" />

  mybatis
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×