MyBatis在注解上使用动态SQL(@select使用if)

dongxurr 2019-12-04

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

3、说明:

如果XML元素嵌入在<script>XML元素中,则可以在注释值中为动态SQL使用XML元素:

@Select("<script>SELECT ...</script>")

但是使用<include>元素会触发SQL Mapper配置解析异常,由以下原因引起:

org.apache.ibatis.builder.BuilderException: Unknown element in SQL statement. at org.apache.ibatis.scripting.xmltags.XMLScriptBuilder.parseDynamicTags

如果nodeHandlers在课堂中检查方法org.apache.ibatis.builder.BuilderException,将注意到支持的元素有:

  • trim
  • where
  • set
  • foreach
  • if
  • choose
  • when
  • otherwise
  • bind

然而,包括基于注释的查询中的片段是不可能的。

参考:

https://segmentfault.com/q/1010000006875476(以上内容转自此篇回答)

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

http://www.blogjava.net/dbstar/archive/2011/08/08/355825.html

http://www.jianshu.com/p/03642b807688

https://stackoverflow.com/questions/33129344/is-there-a-way-to-reuse-sql-fragments-in-annotation-based-mybatis-ibatis

 

相关推荐

jiong / 0评论 2020-09-17