这篇文章主要介绍了Mybatis在注解上如何实现动态SQL,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
在注解上实现动态SQL
使用Mybatis注解实现sql语句,但是有些时候有些字段是空的,这时候这个空的字段就要从条件查询语句中删除,这个时候就需要用到动态Sql。
注解的动态语句支持以下
trimwheresetforeachifchoosewhenotherwisebind
@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 >= #{statrMonth} </if>" +
"<if test = \" (statrMonth == null or statrMonth == '') and (endMonth != null and endMonth != '') \"> AND month <= #{endMonth} </if>" +
"<if test = \" (statrMonth != null and statrMonth != '') and (endMonth != null and endMonth != '') \">AND month >= #{statrMonth} AND month <= #{endMonth} </if>" +
"</where>" +
"</script>"})
public List<Examine> getName(Examine examine);判断字符串为空串 用单引号

大于等于用

小于等于用

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程学习网。
编程基础网
本文标题为:Mybatis在注解上如何实现动态SQL
基础教程推荐
猜你喜欢
- Java实现插入排序算法可视化的示例代码 2023-04-23
- java知识点7——面向过程和面向对象、面向对象的内存分析、构造方法 2023-09-01
- Java多线程学习笔记之三内存屏障与Java内存模型 2023-09-01
- RocketMQ Push 消费模型示例详解 2023-05-24
- 关于Java双大括号{{}}的具体使用 2023-03-15
- Spring Cloud Config分布式配置中心使用介绍详解 2023-05-07
- 一文带你搞懂Java中方法重写与方法重载的区别 2023-07-14
- Java List的get方法 2023-10-08
- Java Web开发中过滤器和监听器使用详解 2023-06-30
- MyBatis-Plus自定义通用的方法实现 2023-07-15
