Mybatis 官方文档: https://mybatis.org/mybatis-3/zh/dynamic-sql.html
数据表
CREATE TABLE `blog` (
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
) ENGINE=INNODB CHARSET=utf8 COLLATE=utf8_general_ci;
实体类
public class Blog {
private String id;
private String title;
private String auther;
private java.util.Date createTime;
private int views;
}
开启驼峰命名自动映射
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
if>
select>
trim
xxx
xxx
## 等价于 where 标签
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
trim>
## 等价于 set 标签
<trim prefix="SET" suffixOverrides=",">
...
trim>
where
若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
HashMap hashMap = new HashMap();
hashMap.put("title","java");
hashMap.put("author","自己");
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
where>
select>
set
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
if>
<if test="author != null">
author = #{author},
if>
set>
where id = #{id}
update>
choose
类似 Java 中的 switch
HashMap hashMap = new HashMap();
hashMap.put("title","java");
// hashMap.put("author","自己");
hashMap.put("views", 1000);
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
when>
<when test="author != null">
author = #{author}
when>
<otherwise>
views = #{views}
otherwise>
choose>
where>
select>
我们可以把一些功能抽取出来,方便复用
<sql id="if-title-author">
<if test="title != null">
title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
sql>
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="if-title-author"/>
where>
select>
注意事项
int[] array = new int[]{10, 5000, 9999};
List<Integer> list = new ArrayList<>();
for (int i : array) {
list.add(i);
}
<select id="getBlogIn" parameterType="list" resultType="Blog">
select * from blog
<where>
<if test="list != null and list.size() > 0">
views in
<foreach collection="list" item="id" index="index" open="(" separator="," close=")">
#{id}
foreach>
if>
where>
select>