Mybatis注解动态SQL

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Mybatis注解动态SQL

k55   2022-06-18 我要评论

在注解上实现动态SQL

使用Mybatis注解实现sql语句,但是有些时候有些字段是空的,这时候这个空的字段就要从条件查询语句中删除,这个时候就需要用到动态Sql。

注解的动态语句支持以下

  • trim
  • where
  • set
  • foreach
  • if
  • choose
  • when
  • otherwise
  • bind
@Select({"<script> " +
        "select * from t_user " +
        "where  1=1 " +
        "<if test='userId!=null'> and id = #{userId}</if> " +
        "</script>"})

要加上标签就可以实现条件判断

但是在无法使用大于号 、小于号,那如何解决这问题呢,其实只要把大于号、小于号转义即可

注解方式动态sql写法和注意事项

@Select({"<script>" +
            "select * from tb_examine" +
            "<where> 1 = 1" +
            "<if test = \" employeeId != null and  employeeId != '' \"> AND employee_id = #{employeeId} </if>" +
            "<if test = \" gradeId != null and gradeId != '' \"> AND grade_id = #{gradeId} </if>" +
            "<if test = \" year != null and year != '' \"> AND year like #{year} </if>" +
            "<if test = \" (statrMonth != null and statrMonth != '') and (endMonth == null or endMonth == '') \"> AND month &gt;= #{statrMonth} </if>" +
            "<if test = \" (statrMonth == null or  statrMonth == '') and (endMonth != null and endMonth != '')   \"> AND month &lt;= #{endMonth} </if>" +
            "<if test = \" (statrMonth != null and statrMonth != '') and (endMonth != null and endMonth != '')   \">AND month &gt;= #{statrMonth} AND month &lt;= #{endMonth}  </if>" +
            "</where>" +
            "</script>"})
public List<Examine> getName(Examine examine);

判断字符串为空串 用单引号

大于等于用

小于等于用

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们