3. MyBatis dynamic sql statement

Suppose you have the following requirements:

The query is performed according to the content selected by the user. The content that is not selected is not used as the query condition . When the query condition is not fixed like this, dynamic SQL can be used to solve the problem. Let’s look at the simplest IF tag first.


When the test in the if tag is true, the content wrapped in the if tag will be added to the sql statement, and it will not be added when it is false

Such an if statement is problematic. For example, when the two query conditions do not exist, there is no content after the where in the sql statement . Such an sql statement is wrong, and the where tag is introduced.

 

Content wrapped by where tag:

1. If the first sql statement has and , it will be automatically deleted, so adding and not adding is the same

2. If no sql statement is added to the content wrapped by the where tag, where will not appear

As shown in the figure below, the student information does not meet the test of the if tag , so people and content will not be added to the sql statement

So the spliced ​​sql statement does not appear where

 

choose tag

Like the switch statement in java , the choose tag has two sub-tags, one is when (similar to case ) and the other is otherwise ( similar to default ), if the statement of the when tag is true, it will be executed, and it will return directly after execution without continuing. Execute down, if all the when tags are false, then execute the otherwise tag


foreach tag:

If you need to query, if users with id 1 , 3 , 5 , 7 , 9 directly write the sql query statement, this is the way to check

Selsect name , id ,score,age from tbl_student where id in (13579)

But if you need to query based on the array passed to you, you need to use the foreach tag to concatenate the string


 

collection : specifies what container (array or collection) is the object to be traversed currently

open : what to start with when splicing the traversed content

close : When splicing the traversed content, what will it end with

spearator : When splicing the traversed content, what to split

item : each item unit in the collection to be traversed

If you want to traverse not an array but a collection, just modify the collection to list

 

If the generic type passed in is a custom type, you can receive it like this

 

sql snippet:

For example, in the above case, we have to write a repetitive code such as select name, age, score, id from tbl_student every time . If we use sql fragments, we can avoid writing such repetitive code, but the disadvantage is that the readability is poor, and the flexible.


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325897627&siteId=291194637