Mybatis annotation developed dynamic SQL statement
Guide:
Using mybatis annotations to develop dynamic SQL will be cumbersome and inconvenient, so it is not recommended.
This article uses query as a case to demonstrate dynamic SQL statements.
Note:
Mybatis' dynamic SQL statement development can be divided into three writing methods :
- Script dynamic sql statement
- SQL defined in the method
- Structured sql
0. Case environment:
a. Entity class User
The attribute of the entity class provides get and set methods The
entity class provides the toString () method
b. Interface IUserDao
c. Requirements To
use dynamic sql, execute the findUserByCondition method in the IUserDao interface.
If the username attribute has a value, add the username = value to the query condition.
If the sex attribute has a value, the query condition is also the merchant's sex = value.
Dynamic Sql implementation:
1. Script dynamic sql statement
Copy the dynamic sql statement in xml directly to the annotation, and use the script tag to include it.
2. Define the SQL statement in the method
2.1 You need to define a class specifically for generating dynamic SQL statements. And define a
method in the class specifically for the findUserByCondition () method to generate SQL statements.
2.2 You can use SELECT (), FROM (), WHERE (), etc. to dynamically generate SQL statements in the method.
2.3 Configure this method of this class to the findUserByCondition () method of the interface
Indicates that the sql statement of the query used by this method is provided by the
findUserByConditionSql method of the UserDynaSqlProvider class
3. Structured sql statement
Note: This method is exactly the same as Method 2, except that the syntax when assembling sql statements is slightly different.
3.1 You need to define a class specifically for generating dynamic sql statements. And define a class in the class specifically for
findUserByCondition () method to generate sql statements Methods.
3.2 You can use SELECT (), FROM (), WHERE (), etc. to dynamically generate sql statements in the method.
3.3 Configure this method of this class to the findUserByCondition () method of the interface
Indicates that the sql statement of the query used by this method is provided by the
findUserByConditionSql method of the UserDynaSqlProvider class
Test:
If the test code is as follows:
Then the sql statement produced by the program is:
The result is:
If the test code is as follows:
Then the sql statement produced by the program is:
The result is: