环境搭建
sql语句
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 DEFAULT CHARSET=utf8
-- 插入数据...
实体类
@Data
public class Blog {
private int id;
private String title;
private String author;
//属性名和字段名不一致
private Date createTime;
private int views;
}
if
Mapper
public interface BlogMapper {
List<Blog> queryBlogIf(Map<String,Object> map);
}
Mapper.xml
满足test
的条件就在sql
后拼接语句
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from blog where 1=1
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</select>
where
使用where
去掉where 1=1
<select id="queryBlogWhere" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</where>
</select>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
choose
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素
,它有点像 Java 中的 switch
语句。
当满足一个when
的test
条件就会在sql
后拼接,不会再向下执行,如果一个条件都没满足就拼接otherwise
内的语句
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title !=null">
and title=#{title}
</when>
<when test="author !=null">
and author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
set
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
<update id="queryBlogSet" parameterType="map">
update blog
<set>
<if test="title !=null">
title=#{title},
</if>
<if test="author !=null">
author=#{author},
</if>
</set>
where id=#{id}
</update>
trim
如果上面的元素无法满足需求可以使用trim
定制元素
如果 where
元素与你期望的不太一样,你也可以通过自定义 rim
元素来定制 where
元素的功能。比如,和 where
元素等价的自定义 trim
元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
prefixOverrides
属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides
属性中指定的内容,并且插入 prefix
属性中指定的内容。
来看看与 set
元素等价的自定义 trim
元素吧:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
注意,我们覆盖了后缀值设置,并且自定义了前缀值。
foreach
你可以将任何可迭代对象(如 List
、Set
等)、Map
对象或者数组对象作为集合参数传递给 foreach
。当使用可迭代对象或者数组时,index
是当前迭代的序号,item
的值是本次迭代获取到的元素。当使用 Map
对象(或者 Map.Entry
对象的集合)时,index
是键,item
是值。
<!--select * from blog where (id=1 or id=2 or id=3)-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
sql片段
抽取公共代码,引入标签,可复用
<sql id="if-title-author">
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</sql>
<select id="queryBlogWhere" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>