标签:XML use ast color where blog template method list
1、用script
标签包围,然后像xml语法一样书写
@Select({"<script>", "SELECT * FROM tbl_order", "WHERE 1=1", "<when test=‘title!=null‘>", "AND mydate = #{mydate}", "</when>", "</script>"})
2、用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
。
参考:
https://segmentfault.com/q/1010000006875476(以上内容转自此篇回答)
MyBatis在注解上使用动态SQL(@select使用if)
标签:XML use ast color where blog template method list
原文地址:http://www.cnblogs.com/EasonJim/p/7449699.html