mybatis中的动态SQL(IF Chooes When Where Set ForEach SQL片段)
mapper:
public interface BlogMapper {
List<Blog> getBlogByIF(Map map);
}
IF
<select id="getBlogByIF" resultType="blog" parameterType="map"> select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
if标签会根据你传入的值去匹配符合条件的if语句
where标签会根据你的传入的值动态的帮助你去掉and
比如:
你传入了title="xxx",那么它的SQL语句会是 select * from blog where title = (你传入的值)
SQL片段
SQL片段是放置重复的语句,提高重用性
例如上述的代码中的
<if test="title != null"> and title = #{title} </if> <if test="author != null"> and author = #{author} </if>
此时,我们可以用<sql></sql>标签 id是唯一标识
<sql id="select"> <if test="title != null"> and title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql>
则我们的查询语句可以简化成下面的样子
<select id="getBlogByIF" resultType="blog" parameterType="map"> select * from mybatis.blog <include refid="select"></include> </select>
refid就是引用上述sql标签中的唯一标识
choose when otherwise
mapper:
public interface BlogMapper { List<Blog> getBlogByChoose(Map map); }
<select id="getBlogByChoose" 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>
其实就是相当于java中的switch语句
传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为按“views”查找的 BLOG
Set
mapper:
public interface BlogMapper {
int updateBlog(Map map);
}
<update id="updateBlog" parameterType="map"> update mybatis.blog <set> <if test="title!=null"> title = #{title}, </if> <if test="author!=null"> author = #{author} </if> </set> where id = #{id} </update>
<set>标签会动态的帮你去掉逗号
ForEach
mapper:
public interface BlogMapper { List<Blog> getBlogForEach(Map map); }
//原始的sql为
//select * from mybatis.blog where (id=1 or id=2 or id=3);
<select id="getBlogForEach" parameterType="map" resultType="blog"> select * from mybatis.blog <where> <foreach collection="list" item="id" open="(" close=")" separator="or"> id = #{id} </foreach> </where> </select>
测试类:
@Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Map map = new HashMap(); ArrayList<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); map.put("list",list); List<Blog> blogs = mapper.getBlogForEach(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。
提示
你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。
当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

浙公网安备 33010602011771号