动态Sql
动态Sql-if
if : 通过判断语句,来动态的加入条件
- blogMapper接口实现
List<Blog> getINforByIF(Map map);
- blogMapper.xml实现
<!--sql片段-->
<sql id="sqlid">
<if test="title !=null">
title=#{title}
</if>
<if test="author !=null">
and author=#{author}
</if>
<if test="views !=null">
and views=#{views}
</if>
</sql>
<select id="getINforByIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="sqlid" />
</where>
</select>
动态Sql-choose
choose: 可以类比于Switch语句
- 接口实现
List<Blog> getINforByChoose(Map map);
- 对应的.xml实现
<select id="getINforByChoose" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title !=null">
title=#{title}
</when>
<when test="author !=null">
and author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
动态Sql-set
- 接口实现
int update1(Map map);
- 对应的.xml实现
<update id="update1" parameterType="map" >
update mybatis.blog
<set>
<if test="title !=null">
title=#{title},
</if>
<if test="author !=null">
author=#{author},
</if>
<if test="views !=null">
views=#{views}
</if>
</set>
where id=#{id}
</update>
动态Sql-foreach
- 接口实现
List<Blog> getINforByForEach(Map map);
- 对应接口的.xml实现
<select id="getINforByForEach" parameterType="map" resultType="blog">
select * from mybatis.blog where id in
<foreach collection="idList" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
foreach参数介绍
idList:遍历的对象
id:遍历出的值
open,close:开始,结束符号
separator:分隔符