美文网首页springboot
springboot 集合mybatis 注解版,动态sql语句

springboot 集合mybatis 注解版,动态sql语句

作者: DeleteDatabase | 来源:发表于2019-07-25 10:57 被阅读0次

大多数mybatis基本都用xml 配置。而今天再用注解版mybatis就遇到了个问题,我比如要查询一句有多条件的数据,但是该数据具体不知道是否为空,这时候我考虑到了要用动态sql语句来写。像xml有if可以来判断值是否为空,注解版该怎么处理呢?


image.png
@Select("<script>select id,create_time as createTime," +
            "update_time as updateTime,is_del as isDel ," +
            "phone_number as phoneNumber,password,sex,status,username" +
            " from com_admin where is_del = 0 " +
            "<if test=\"keyword !=null and keyword != ''\">and username like #{keyword}</if> " +
            "<if test=\"startTime!=null and startTime!=''\">and create_time > #{startTime}</if>" +
            "<if test=\"endTime!=null and endTime!=''\">and create_time < #{endTime}</if></script>  ")
    List<AdminAllMessage> search(String keyword, String startTime, String endTime);

思考

注解版是让我们输入一串字符串,肯定不能直接使用xml的写法

所以我们需要<script></script>这一串标记来解决这个问题
将自己sql语句代码输入进@select注解中就好了,你以为结束了嘛?这时候就会遇到了bug了
由于在这个script中不能在使用< ,>, <>符号,所以用这些符号的都会报错。那该怎么办?

image.png
@Select("<script>select id,create_time as createTime," +
            "update_time as updateTime,is_del as isDel ," +
            "phone_number as phoneNumber,password,sex,status,username" +
            " from com_admin where is_del = 0 " +
            "<if test=\"keyword !=null and keyword != ''\">and username like #{keyword}</if> " +
            "<if test=\"startTime!=null and startTime!=''\">and create_time &gt; #{startTime}</if>" +
            "<if test=\"endTime!=null and endTime!=''\">and create_time &lt; #{endTime}</if></script>  ")
    List<AdminAllMessage> search(String keyword, String startTime, String endTime);

通过& lt; & gt;符号来解决 <,>无法使用的问题。这时候你就可以快乐的写注解了

相关文章

  • springboot 集合mybatis 注解版,动态sql语句

    大多数mybatis基本都用xml 配置。而今天再用注解版mybatis就遇到了个问题,我比如要查询一句有多条件的...

  • MyBatis 注解方式的基本用法

    什么是MyBatis的注解方式 MyBatis的注解方式就是将SQL语句直接写在接口上。在MyBatis注解SQL...

  • MyBatis 动态SQL(*.xml)

    原文参考MyBatis 动态SQL MyBatis的动态SQL大大减少了拼接SQL语句时候的各种格式问题,这里摘录...

  • mybatis 注解使用 Day14 2018-12-02

    三、注解配置 select。映射查询SQL语句 selectProvider。select语句的动态SQL映射。 ...

  • 02.MyBatis映射文件深入

    1.1 动态sql语句 1. 动态sql语句概述 Mybatis 的映射文件中,前面我们的 SQL 都是比较简单的...

  • MyBatis学习:动态sql

    1.动态sql 动态sql是mybatis中的一个核心,什么是动态sql?动态sql即对sql语句进行灵活操作,通...

  • 第八章 动态SQL

    动态SQL中的元素介绍 动态SQL有什么作用 MyBatis提供了对SQL语句动态组装的功能 动态SQL中的元素 ...

  • IT 每日一结

    mybatis动态sql 动态sql绝对是mybatis排列前几的闪光点之一。传统代码中的sql语句需要经过多个字...

  • Mybatis入门(三)之动态sql

    Mybatis入门之动态sql 动态拼接sql语句,在我的理解就是相当于Java中的逻辑控制语句(if,,swit...

  • MyBatis的注解开发

    MyBatis的注解开发MyBatis的映射配置除了使用xml配置以外,还支持注解配置sql语句问题: 为什么有了...

网友评论

    本文标题:springboot 集合mybatis 注解版,动态sql语句

    本文链接:https://www.haomeiwen.com/subject/nopcrctx.html