【Video & Communication Platform】
http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share
http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share
https://gitee.com/happyangellxq520/spring-boot
à Spring Boot communication platform
http://412887952-qq-com.iteye.com/blog/2321532
[This blog has a supporting video, the video address: " Spring Boot MyBatis Upgrade - Annotation - Dynamic SQL (if test) - Scheme 1 script " , click the following to read the original text in the official account, and the video explains in more detail]
Origin of need:
Netizen 1 : How to solve the query if it is an indefinite condition? That is , if tags can be used in xml , what about annotations?
Netizen 2 : This dynamic sql is not very convenient to use annotations! There is a good way for bloggers, please refer to it, the reason why the annotation has not been used is that there is no good way for dynamic sql , including when foreach ! For simple queries it's still ok!
The blogger is very relieved to see such positive questions from netizens. If there is a problem, he will study it.
Demand scenario:
When we query a table with id, name, and email, we hope that when the name is not null , it will be used as the query condition, and if the email is not null , it will be used as the query condition.
Implementation process:
( 1 ) name, email and relationship
如果name和email只是并且的关系的话,那么我们会这么写:
@Select("Select * from Demo where name =#{name} and email=#{email} ")
public List<Demo> select3(Demo demo);
其中Demo类如下:
public class Demo { private int id; private String name; private String email; private Date updateTime; private SexEnum sexEnum; //省略getter and setter… }
表中的数据:
2 王五 [email protected] 3 王五 [email protected] 4 王五2 [email protected] 5 王五6 [email protected]
这时候访问:
http://127.0.0.1:8080/select3?name=王五&[email protected] 能返回数据。
但是现在我们的需求不是这样的了。
(2)if name !=null ,if email != null
现在我们希望的是如果name不为null的话,那么就当做条件,否则就不要当做条件;如果email不为null,那么就当做条件,否则不当做条件。
那么方案一:so eay,只需要在前面加入<script>就可以使用<if test>标签了,代码如下:
@Select("<script> " + "SELECT * " + "from Demo " + " <where> " + " 1=1" + " <if test=\"name != null\">and name=#{name}</if> " + " <if test=\"email != null\"> and email=#{email}</if> " + " </where> " + " </script> ") public List<Demo> select4(Demo demo);
访问1:http://127.0.0.1:8080/select4会返回全部数据,动态SQL是:
SELECT * from Demo WHERE 1=1
访问2:http://127.0.0.1:8080/select4?name=王五 会返回name=王五的数据,动态SQL是:
SELECT * from Demo WHERE 1=1 and name=?
访问3:http://127.0.0.1:8080/select4?name=王五&[email protected]会返回name=王五并且[email protected]的数据,动态SQL是:
SELECT * from Demo WHERE 1=1 and name=? and email=?
是不是很酷,完美解决问题。但是后头看代码这样的代码可读性差,修改的时候也很麻烦,所以呢,是否有更好的方案呢?下篇博客揭晓,广告时刻,大家不要离开。
视频&交流平台:
http://study.163.com/course/introduction.htm?courseId=1004329008
http://412887952-qq-com.iteye.com/blog/2321532