温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Mybatis在注解上怎么实现动态SQL

发布时间:2022-06-13 15:51:02 来源:亿速云 阅读:772 作者:iii 栏目:开发技术

本文小编为大家详细介绍“Mybatis在注解上怎么实现动态SQL”,内容详细,步骤清晰,细节处理妥当,希望这篇“Mybatis在注解上怎么实现动态SQL”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

在注解上实现动态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>"})

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

Mybatis在注解上怎么实现动态SQL

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

Mybatis在注解上怎么实现动态SQL

Mybatis在注解上怎么实现动态SQL

注解方式动态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);

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

Mybatis在注解上怎么实现动态SQL

大于等于用

Mybatis在注解上怎么实现动态SQL

小于等于用

Mybatis在注解上怎么实现动态SQL

读到这里,这篇“Mybatis在注解上怎么实现动态SQL”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI