Dynamic SQL is the core of MyBatis, which is the flexible operation of our SQL statements, which can be used to judge SQL statements by Expressions , and then to make flexible stitching and assembling. Can be simply said that the mybatis can be dynamic to judge the need for something.
Dynamic SQL has the following main types:
If
Choose,when,otherwise
Trim,where,set
Foreach
Here are a few common where if foreach, direct code
1.where where there is a good thing is that when stitching succeeds, it automatically removes the first and
2.if here if and Java based on the if usage is the same, the usage here is when the condition is set up, the SQL statement will be stitched up, when the non-establishment of the SQL statement will be ignored
3.if can be repeated and nested using
4. The student.name here is the packing class
foreach usage: Find the SID in the 4,5,6,7 students
<!--test foreach code--><sql id= "Foreache" > <if test= "Sid_s!=null" > <!-- Collection: Specifies the properties of the collection you entered item: Object Name (alias) for each traversal open: the string to be stitched when the traversal is started close: the strings to be stitched when the traversal is over Separator: The string to be spliced in the middle of the traversed object * from the t_student WHERE SID in (4,5,6,7); --<foreach collection= "sid_s" item= "Sid" Open= "and Sid in (" close= ")" separator= "," > #{sid} </foreach> </if> </sql>
SQL fragment: (improves reusability of SQL code in the configuration file)
SQL Fragment notation:
<!-- ID: This is the only way to identify the SQL snippet experience: SQL code reuse based on single-table writes is High " : just don't appear in the SQL code where--< SQL id= "Query_list" > <if test= "Student!=null and student!=" "> <if test=" Student.name!=null and student.name!= ' "> and name=#{student.name} </ If> <if test= "Student.sex!=null and student.sex!=" > and sex= #{student.sex} </if> </if></sql>
References to SQL fragments: (SQL fragments that can reference other configuration files: namespaces. The ID of the SQL fragment)
<!--Stitching succeeds, this where will automatically remove the first and-- <where> <include refid= "Query_list" ></include > </where>
Dynamic SQL and SQL fragments in 6.Mybatis (one core of MyBatis)