mybatis 使用map完成select多个筛选条件
select使用map完成多个筛选条件
- 可以使用foreach中collection="map"来进行遍历,item 等价 value, index 等价 key,使用separator=“and”表示筛选条件并列。其中使用了choose when otherwise标签做判断,类似于switch的效果
- list等数据结构也能如此,item等价于每一项的数据就行了
- 注意:大家都明白mybatis中‘#’ 和 ’$‘符号的区别,所以在对列名的映射的时候需要使用‘$’,这样才会使列名不会被双引号包起来,如果包起来那么检索条件不会成立
<select id="selectByConditions" resultType="com.tz.model.User">
select * from `user1`
where
<foreach collection="map" item="item" index="index" separator="and" open="(" close=")">
<choose>
<when test="item != null">
${index} = #{item}
</when>
<otherwise>
1
</otherwise>
</choose>
</foreach>
</select>
结果:
Preparing: select * from `user1` where ( 1 and password = ? and userName = ? ) or ( 1 or password = ? or userName = ? )
==> Parameters: aaaa(String), aaaa(String), aaaa(String), aaaa(String)
<== Total: 33