spring Mybatis注解加判断
一、用script标签包围,然后像xml语法一样书写
1. 判断参数是否为空或者为null,没有参数则不执行该语句
/** * @description 根据条件查询客户信息 (分页查询) 倒叙 * - asc 按升序排列 (不用写,默认使用这个) * - desc 按降序排列 */ @Select({"<script>","select * from user","where 1=1", "<if test='tel!=null and tel!=\"\"'>","and tel = #{tel}","</if>", "<if test='customname!=null and customname != \"\"'>","and customname = #{customname}","</if>", "<if test='sendemail!=null and sendemail !=\"\"'>","and send_email = #{sendemail}","</if>", "<if test='keywords!=null and keywords != \"\"'>","and keywords like '%${keywords}%'","</if>", "order by id desc limit #{pages},#{limit}", "</script>"}) public List<Custom> findCustomByForm(@Param("tel") String tel,@Param("customname") String customname, @Param("sendemail") String sendemail,@Param("keywords") String keywords, @Param("pages") Integer pages,@Param("limit") Integer limit);
注意:此处判断空时用到转义字符 name != \"\"
2. 多个判断中取出一个类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。
/** * @description 根据条件查询客户信息 (分页查询) 倒叙 * - asc 按升序排列 (不用写,默认使用这个) * - desc 按降序排列 */ @Select({"<script>","select * from user","where 1=1", "<choose><when test='tel!=null'>","and tel = #{tel}","</when>", "<when test='customname!=null'>","and customname = #{customname}","</when>", "<when test='sendemail!=null'>","and send_email = #{sendemail}","</when>", "<when test='keywords!=null'>","and keywords like '%${keywords}%'","</when></choose>", "order by id desc limit #{pages},#{limit}", "</script>"}) public List<Custom> findCustomByForm(@Param("tel") String tel,@Param("customname") String customname, @Param("sendemail") String sendemail,@Param("keywords") String keywords, @Param("pages") Integer pages,@Param("limit") Integer limit);
注意:有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。而使用if标签时,只要test中的表达式为 true,就会执行 if 标签中的条件。MyBatis 提供了 choose 元素。
if标签是与(and)的关系,而 choose 是或(or)的关系。
choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。
当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。
同样把所有可以限制的条件都写上,方面使用。choose会从上到下选择一个when标签的test为true的sql执行。安全考虑,我们使用where将choose包起来,放置关键字多于错误。
二、用Provider去实现SQL拼接,例如:
public class OrderProvider { private final String TBL_ORDER = "tbl_order"; public String queryOrderByParam(OrderPara param) { SQL sql = new SQL().SELECT("*").FROM(TBL_ORDER); String room = param.getRoom(); if (StringUtils.hasText(room)) { sql.WHERE("room LIKE #{room}"); } Date myDate = param.getMyDate(); if (myDate != null) { sql.WHERE("mydate LIKE #{mydate}"); } return sql.toString(); } } public interface OrderDAO { @SelectProvider(type = OrderProvider.class, method = "queryOrderByParam") List<Order> queryOrderByParam(OrderParam param); }
注意:方式1有个隐患就是当传入参数为空的时候,可能会造成全表查询。
复杂SQL用方式2会比较灵活(当然,并不建议写复杂SQL),而且可以抽象成通用的基类,使每个DAO都可以通过这个基类实现基本的通用查询,原理类似Spring JDBC Template。
追崇技术,乐在分享!