在实际项目开发中,sql的编写起了关键作用。
如果想复用自定义的多条件查询功能,实现一个sql就能支持大多数的查询,那循环<foreach/>和选择<choose/>标签绝对是一大利器,再配上万能map,绝对值得使用和推荐。
1.存在如下的mapper接口信息(利用万能map动态传参)
List<PlanBudget> diySelectPlanBudgetList(Map<String,Object> params);
2.万能map动态参数举例说明:
其中currentStr是自定义时间参数,根据自己实际处理,ids是数组。
Map<String,Object> params = new HashMap<>();
String currentStr = DateCommonUtils.DEFAULT_DATETIME_FORMATE.format(new Date());
params.put("endStr",currentStr);
params.put("status_info","00");
params.put("status",1);
params.put("qoutaType","05");
params.put("ids",new int[]{1,3});
3.对应xml的写法:
属性及写法详解:
- <foreach/>
collection:对应map中的属性名称,也就是map参数中的ids;
item:该参数相当于循环变量,可以任意自定义,但是须与in子句的取值保持一样;
其他参数保存固定写法即可。
- <choose/>
该标签不能单独使用,须与<when/>标签连用,用法与if判断语句类型,具体可参考如下。
- 大于,小于的写法
由于xml规范不可以直接使用五个保留字符,“ < > & ” ’ ”
因此在mybaits的xml中,大于或者小于要按照如下规则进行编写:>
要写成 >
<
要写成 <
>=
要写成 >=
<=
要写成 <=
<select id="diySelectPlanBudgetList" parameterType="map" resultType="com.test.plan.entity.PlanBudget">
select *
from plan_budget
<where>
del_flag = '0'
<if test="ids != null and ids.length > 0">
and id in
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</if>
<if test="status != null "> and status = #{status}</if>
<choose>
<when test="description != null and description != ''">
and description = #{description}
</when>
<otherwise>
and description is null
</otherwise>
</choose>
<choose>
<when test="status_info != null and status_info == '00'">
<if test="startStr != null and startStr != ''"> and DATE_FORMAT(plan_start,'%Y-%m-%d %H:%i:%s') < #{startStr}</if>
<if test="endStr != null and endStr != ''"> and DATE_FORMAT(plan_end,'%Y-%m-%d %H:%i:%s') > #{endStr}</if>
</when>
<when test="status_info != null and status_info == '01'">
<if test="endStr != null and endStr != ''"> and DATE_FORMAT(plan_end,'%Y-%m-%d %H:%i:%s') < #{endStr}</if>
</when>
</choose>
</where>
</select>