Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka
MyBatis the operation of the database, sometimes with some conditions, so the dynamic SQL statement is very necessary, the following is mainly about the syntax of several commonly used dynamic SQL statements
The elements used to implement dynamic SQL in MyBatis are:
1. If
Judge the property, and if it is not empty, the judging condition is executed.
<select id= "Selectbycriteria" parametertype= "com.mucfc.dto.Student" resultmap= "Baseresultmap" >select * from T_ Student where<if test= "Stuid! = null and Stuid! =" ">stu_id = #{stuid}</if><if test=" Stuname! = null and St UName! = "" >and stu_name = #{stuname}</if><if test= "Stuclass! = null and Stuclass! = '" ">and Stu_class = #{ Stuclass}</if><if test= "Stusex! = null and Stusex! =" ">and stu_sex=#{stusex}</if><if test=" Stuage! = null and Stuage! = "" >and stu_age=#{stuage}</if></select>
Let's look at the results:
This is the parameter entered from the Web page
This is the result of the output
This is the printed SQL statement.
As you can see from the results, the property is assigned only if the condition is not empty.
2. Where
when where The conditions used in the if This combination can cause errors when the labels are large. We use the query statement in 1 as an example, when the input parameter stuid is empty, will be an error
Then the result of the output:
At this point the SQL statement becomes the SELECT * from T_student where and stu_sex=? This will cause an error.
If the above example, the parameter stuid is null, will not be judged by the Student_name column, it will direct the "WHERE and" keyword extra error SQL. At this point we can use the where dynamic statement to resolve. The "where" tab will know if it contains a return value in the tag, it will insert a ' where '. In addition, if the label returns content that begins with and or or, it is removed.
Can be changed to the following:
<select id= "Selectbycriteria" parametertype= "com.mucfc.dto.Student" resultmap= "Baseresultmap" >select * from T_ Student <where><if test= "Stuid! = null and Stuid! =" ">stu_id = #{stuid}</if><if test=" Stuname! = nul L and Stuname! = "" ">and stu_name = #{stuname}</if><if test=" Stuclass! = null and Stuclass! = "" >and STU_CL #{stuclass}</if><if test= "Stusex! = null and Stusex! =" ">and stu_sex=#{stusex}</if><if test= "Stuage! = null and Stuage! =" ">and stu_age=#{stuage}</if></where></select>
Take a look again and enter the query criteria
And then output the results
Print out the SQL statement
-==> Preparing:select * from T_student WHERE stu_sex=?
==> Parameters: Male (String)
<== total:14
Indicates that the result is correct. If it contains a label that has a return value, insert a where. In addition, if the label returns content that begins with and or or, it is removed.
3. Set
When the IF tag is not used in the UPDATE statement, an error is caused if one of the arguments is null.
If the IF tag is used in an UPDATE statement, or if the preceding if is not executed, it causes a comma superfluous error. The set label allows you to configure the dynamic configuration of the Set keyword, and to reject any unrelated commas appended to the end of the condition.
When modified with the if+set tag, if an item is NULL, it is not updated, but the database's original value is maintained. The following example:
4. Trim
Trim is a more flexible place for the label of superfluous keywords, and he can practice the effects of where and set .
<select id= "Selectbycriteria" parametertype= "com.mucfc.dto.Student" resultmap= "Baseresultmap" >select * from T_ Student <trim prefix= "where" prefixoverrides= "And|or" > <if test= "Stuid! = null and Stuid! =" ">stu_id = # {stuid}</if><if test= "Stuname! = null and Stuname! = '" ">and stu_name = #{stuname}</if><if test=" STU Class! = null and Stuclass! = "" >and stu_class = #{stuclass}</if><if test= "Stusex! = null and Stusex! =" "> and stu_sex=#{stusex}</if><if test= "Stuage! = null and Stuage! =" ">and stu_age=#{stuage}</if></ Trim></select>
First, determine if the where is needed, and if necessary, it will automatically determine if there are and or or in the back, and automatically remove them. The prefix is pre-placed, and the suffix is behind.
The following input finds the parameter stuclass=2.
Look at the printed statement.
Suffix is an example of a post-placement
<insert id= "Insert" parametertype= "com.mucfc.dto.Student" > insert INTO t_student <trim prefix= "(" suffix= ")" suffixoverrides= "," > <if test= "Stuid! = null" > stu_id, </if> <if test= "stu_name!= null" > stu_name, </if> </trim> <trim prefix= "VALUES (" suffix= ")" Suffixoverrides= "," > <if test= "stuid! = null" > #{stuid}, </if> <if test= "St U_name! = null "> #{stu_name}, </if></insert
Here is the automatic judgment is empty, and then remove the comma
Prefix= "(" suffix= ")"
will automatically determine if it is necessary to add () this symbol
5, choose
Sometimes we don't want to apply all the conditions, but just want to choose one of the multiple options. When using the If label, the condition in the If label is executed whenever the expression in test is true. MyBatis provides the Choose element. The IF tag is a relationship with (and), while choose is or (or).
Choose tags are in order to determine the internal when tag in the test condition is set, if there is a set, then choose End. When all of the when conditions in choose are not satisfied, then the SQL in otherwise is executed. A switch statement similar to Java, choose Switch,when to Case,otherwise is default.
<!--meet one of the conditions with choose when Operation--><select id= "Selectbycriteria" parametertype= "Com.mucfc.dto.Student" resultmap= "Baseresultmap" >select * from T_student <where> <choose> <when test= "Stuid ! = null and Stuid! = "" > stu_id = #{stuid} </when> <when test= "Stuclass! = null and Stuclass! =" " > stu_class = #{stuclass} </when> <otherwise> </otherwise> </ choose> </where> </select>
Enter two parameters
This parameter is skipped for Harry because Stuid is not empty
Then look at the printed statement, sure enough only one condition, so the explanation is right
foreach
very necessary for dynamic SQL, the primary is to iterate over a collection, typically for in Conditions. The list instance uses "list" as the key, and the array instance takes "array" as the key. The
foreach element is very powerful and allows you to specify a collection that declares collection items and index variables that can be used within an element body. It also allows you to specify open and closed strings and place delimiters between iterations. This element is very intelligent and does not accidentally append extra separators.
Note: You can pass a list instance or an array as a parameter object to MyBatis. When you do this, MyBatis will automatically wrap it in a map, using the name as the key. The list instance will be "list" as the key, and the array instance will be "array" as the key.
The main use of foreach is in the build in condition, which can iterate a collection in an SQL statement. The properties of the Foreach element are mainly item,index,collection,open,separator,close. The item represents the alias of each element in the collection when it iterates, and index specifies a name that represents the position at which each iteration occurs during the iteration, and open indicates what the statement begins with, and separator indicates what symbol is used as the delimiter between each iteration. Close means the end, the most critical and error-prone when using foreach is the collection property, which must be specified, but in different cases the value of the property is not the same, there are 3 main cases:
If a single parameter is passed in and the parameter type is a list, the collection property value is List
If a single parameter is passed in and the parameter type is an array, the value of the collection property is array
If the parameters passed in are multiple, we need to encapsulate them into a map, of course, the single parameter can also be encapsulated as a map, in fact, if you pass in the parameter, in the MyBatis will also wrap it into a map, the map key is the parameter name, So this time the collection property value is the key to the incoming list or array object in its own encapsulated map
Here's a look at the sample code for each of the three scenarios:
1. Type of single parameter list:
The value of the above collection is list, the corresponding Mapper is this
Test code:
2. Type of single-parameter array arrays:
The above collection is an array, corresponding to the mapper code:
The corresponding test code:
@Testpublic void Dynamicforeach2test () {sqlsession session = Util.getsqlsessionfactory (). Opensession (); Blogmapper blogmapper = Session.getmapper (Blogmapper.class); int[] ids = new int[] {1,3,6,9}; list<blog> blogs = blogmapper.dynamicforeach2test (IDs); for (blog blog:blogs) System.out.println (blog); Session.close ();}
3. Encapsulate the parameters as a map type
The value of the above collection is IDs, which is the key of the incoming parameter map, corresponding to the mapper code:
Public list<blog> dynamicforeach3test (map<string, object> params);
Corresponding Test code:
6. Joint Example:
<insert id= "Batchinserttrxbilldetailinfo" parametertype= "Java.util.Map" >insert all<foreach collection= " List "item=" item ">into trx_bill_detail_info <trim prefix=" ("suffix=") "suffixoverrides=", "> <if test = "Item.id! = NULL" > ID, </if> <if test= "Item.custno! = null" > Cust_no, </ if> <if test= "Item.transcode! = null" > Trans_code, </if> <if test= "Item.transrefn O! = null "> trans_refno, </if> <if test=" Item.transseqno! = null "> Trans_seqno, </if> <if test= "Item.orderno! = null" > Order_no, </if> <if test= "Item.tran SAMT! = null "> Trans_amt, </if> <if test=" Item.billdate! = null "> Bill_date, </if> <if test= "Item.billflag! = null" > Bill_flag, </if> <if test= "Item.trans Desc! = null "> TRANS_desc, </if> </trim> <trim prefix= "VALUES (" suffix= ")" suffixoverrides= "," > <if tes T= "Item.id! = null" > #{item.id,jdbctype=decimal}, </if> <if test= "Item.custno! = null" > #{item.custno,jdbctype=char}, </if> <if test= "Item.transcode! = null" > #{item.transco De,jdbctype=char}, </if> <if test= "ITEM.TRANSREFNO! = null" > #{item.transrefno,jdbctype=char }, </if> <if test= "Item.transseqno! = null" > #{item.transseqno,jdbctype=varchar}, </ if> <if test= "OrderNo! = null" > #{item.orderno,jdbctype=char}, </if> <if test= "it Em.transamt! = null "> #{item.transamt,jdbctype=decimal}, </if> <if test=" Item.billdate! = Nu ll "> #{item.billdate,jdbctype=decimal}, </if> <if test=" Item.billflag! = null "> # {item.billflag,jdbctype=CHAR}, </if> <if test= "Item.transdesc! = null" > #{item.transdesc,jdbctype=varchar}, < ;/if> </trim> </foreach> Select 1 from dual </insert>
Copyright NOTICE: This article for Bo Master Lin Bingwen Evankaka original article, without Bo Master permission not reproduced.
MyBatis Dynamic SQL statements