1. 程式人生 > >MyBatis在註解上使用動態SQL(@select使用if)

MyBatis在註解上使用動態SQL(@select使用if)

quest param select derby where 1=1 color 建議 utils and

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(以上內容轉自此篇回答)

https://stackoverflow.com/questions/6685655/how-to-use-dynamic-sql-query-in-mybatis-with-annotationhow-to-use-selectprovide

MyBatis在註解上使用動態SQL(@select使用if)