使用mybatis的时候常常会用到一些sql ,记录以下:java
1. foreach的使用sql
foreach元素的属性主要有 item,index,collection,open,separator,close。数组
item表示集合中每个元素进行迭代时的别名,mybatis
index指 定一个名字,用于表示在迭代过程当中,每次迭代到的位置,app
open表示该语句以什么开始,函数
separator表示在每次进行迭代之间以什么符号做为分隔 符,测试
close表示以什么结束。code
1.单参数List的类型:blog
Java接口: 接口
List<Map<String, Object>> listRemarkCountByResumeIds(@Param("resumeIds") List<String> resumeIds);
mapper文件中:
<select id="listRemarkCountByResumeIds" parameterType="map" resultType="map"> SELECT COUNT(1) count, RESUME_ID resumeId FROM T_CV_REMARK WHERE RESUME_ID IN <foreach collection="resumeIds" open="(" close=")" item="resumeId" separator=","> #{resumeId} </foreach> AND DEFUNCT = 0 GROUP BY RESUME_ID </select>
2.单参数array数组的类型:
java 接口:
public List dynamicForeach2Test(int[] ids);
mapper文件:
<select id="dynamicForeach2Test" parameterType="java.util.ArrayList" resultType="Blog"> select * from t_blog where id in <foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
3.本身把参数封装成Map的类型
Java 接口:
测试例子: List ids = new ArrayList(); ids.add(1); ids.add(2); ids.add(3); Map params = new HashMap(); params.put("ids", ids); params.put("title", "中国"); List blogs = blogMapper.dynamicForeach3Test(params);
public List dynamicForeach3Test(Map params);
mapper文件:
<select id="dynamicForeach3Test" parameterType="java.util.HashMap" resultType="Blog"> select * from t_blog where title like "%"#{title}"%" and id in <foreach collection="ids" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
2. like模糊查询
<!-- ******************** 模糊查询的经常使用的3种方式:********************* --> <select id="getUsersByFuzzyQuery" parameterType="User" resultType="User"> select <include refid="columns"/> from users <where> <!-- 方法一: 直接使用 % 拼接字符串 注意:此处不能写成 "%#{name}%" ,#{name}就成了字符串的一部分, 会发生这样一个异常: The error occurred while setting parameters, 应该写成: "%"#{name}"%",即#{name}是一个总体,先后加上% --> <if test="name != null"> name like "%"#{name}"%" </if> <!--方法二: 使用concat(str1,str2)函数将两个参数链接 --> <if test="phone != null"> and phone like concat(concat("%",#{phone}),"%") </if> <!--方法三: 使用 bind 标签,对字符串进行绑定,而后对绑定后的字符串使用 like 关键字进行模糊查询 --> <if test="email != null"> <bind name="pattern" value="'%'+email+'%'"/> and email like #{pattern} </if> </where> </select>
3. find_in_set
Java接口:
int countHhByCondition(@Param(value = "queryParam") Map<String, Object> queryParam);
其中 queryParam参数中 positions 是一个List 集合
mapper文件:
<if test="queryParam.positions != null and queryParam.positions.size() >0"> <foreach collection="queryParam.positions" item="id" open="(" close=")" separator="OR"> FIND_IN_SET(#{id} ,expert.EXPERT_POSITION) </foreach> </if>
4. if 条件的判断
在进行if条件判断 等于的时候要注意使用下面这种: 【 x == 'A'.toString() 】
<if test="grade!= null and grade!= '' and grade == '1'.toString()"> name = #{grade} </if>