The basic usage of dynamic SQL in the Java MyBatis Framework is detailed _java

Source: Internet
Author: User

In some cases, the SQL statement where condition requires some security judgments, such as if the incoming parameter is empty when the query is in a certain condition, the result of the query is likely to be empty, and maybe we need to find out all the information when the parameter is empty. Use Oracle's sequence, MySQL's function to generate IDs. Then we can use dynamic SQL. MySQL syntax and functions (such as String link function concat) are used below.

Selectkey Label
in the INSERT statement, Oracle often uses sequences, uses functions in MySQL to automatically generate primary keys for inserting tables, and requires methods to return the generated primary key. This effect can be achieved by using the MyBatis selectkey tag. The following example uses the MySQL database custom function nextval (' student ') to generate a key and set it to the StudentID attribute in the incoming entity class. So after this method is executed, the edge can get the generated key through the entity class.

<!--insert Student automatic primary key--> 
<insert id= "Createstudentautokey" parametertype= " Liming.student.manager.data.model.StudentEntity "keyproperty=" StudentID "> 
 <selectkey keyproperty=" StudentID "resulttype=" String "order=" before "> 
  select Nextval (' Student ') 
 </selectKey> 
 INSERT Into Student_tbl (student_id, 
       student_name, 
       student_sex, 
       student_birthday, 
       Student_photo 
       , class_id, 
       place_id) 
 VALUES (#{studentid}, 
   #{studentname}, 
   #{studentsex}, 
   #{ Studentbirthday}, 
   #{studentphoto, javatype=byte[], Jdbctype=blob, typehandler= Org.apache.ibatis.type.BlobTypeHandler}, 
   #{classid}, 
   #{placeid}) 
</insert> 


Calling an interface method, and getting the automatically generated key

studententity entity = new studententity (); 
Entity.setstudentname ("Hello at Dawn"); 
Entity.setstudentsex (1); 
Entity.setstudentbirthday (Dateutil.parse ("1985-05-28")); 
Entity.setclassid ("20000001"); 
Entity.setplaceid ("70000001"); 
This.dynamicSqlMapper.createStudentAutoKey (entity); 
System.out.println ("Add Student ID:" + entity.getstudentid ()); 


Selectkey Statement Property configuration details:

Property Describe Take value
Keyproperty Selectkey statement generates the property that the result needs to set.
Resulttype build the result type, MyBatis allows the use of basic data types, including String , int type.
Order

1 : before , you first select the primary key and then set the Keyproperty , and then execute Insert statement;

2 : After , run first Insert statement to run again Selectkey statement.

Before

After
StatementType MyBatis Support STATEMENT , PREPARED and callable the form of statements, corresponds to Statement ,preparedstatement and CallableStatement Response

STATEMENT

PREPARED

callable

If label

If tags can be used in many types of SQL statements, let's take a query for example. First look at a very common query:

<!--inquiry student list,like name--> 
<select id= "Getstudentlistlikename" parametertype= "studententity" Studentresultmap "> 
 SELECT * from Student_tbl St 
WHERE St. Student_name like CONCAT (CONCAT ('% ', #{studentname}), '% ') 
</select> 

However, if studentname or studentsex is null at this point, this statement is likely to have an error or empty query results. At this point we use the IF dynamic SQL statement first to judge, if the value is null or equal to the empty string, we do not make this condition to judge, increase flexibility.
parameter is an entity class studententity. All attributes in the entity class are judged, and if not NULL, the criteria are executed.

<!--2 if (judgment parameter)-attributes that are not empty for entity classes as where conditions--> <select id= "getstudentlist_if" resultmap= "Resultmap_studententity" p Arametertype= "Liming.student.manager.data.model.StudentEntity" > SELECT ST. student_id, ST. Student_name, ST. Student_sex, ST. Student_birthday, ST. Student_photo, ST. class_id, ST. place_id from Student_tbl St WHERE <if test= "Studentname!=null" > St. Student_name like CONCAT (CONCAT ('% ', #{studentname, Jdbctype=varchar}), '% ') </if> <if test= ' Studentsex!= nul L and Studentsex!= ' "> ST. Student_sex = #{studentsex, jdbctype=integer} </if> <if test= "studentbirthday!= null" > and ST. 
  Student_birthday = #{studentbirthday, jdbctype=date} </if> <if test= "classId!= null and classid!=" "> and ST. class_id = #{classid, Jdbctype=varchar} </if> <if test= "classentity!= null and Classentity.classid!=null D classentity.classid!= ' "> ST. class_id = #{claSsentity.classid, Jdbctype=varchar} </if> <if test= "Placeid!= null and Placeid!=" "> and ST. place_id = #{placeid, Jdbctype=varchar} </if> <if test= "placeentity!= null and Placeentity.placeid!= null a nd placeentity.placeid!= ' "> ST. place_id = #{placeentity.placeid, Jdbctype=varchar} </if> <if test= "StudentID!= null and StudentID!=" "&G 
  T and ST. 
 student_id = #{studentid, Jdbctype=varchar} </if> </select>

Use more flexible, new one such entity class, we need to limit that condition, only need to attach the corresponding value will be where this condition, instead of assigning value can not be judged in the where.

public void Select_test_2_1 () { 
 studententity entity = new studententity (); 
 Entity.setstudentname (""); 
 Entity.setstudentsex (1); 
 Entity.setstudentbirthday (Dateutil.parse ("1985-05-28")); 
 Entity.setclassid ("20000001"); 
 Entity.setplaceid ("70000001"); 
 list<studententity> list = this.dynamicSqlMapper.getStudentList_if (entity); 
 for (studententity e:list) { 
  System.out.println (e.tostring ()); 
 } 
} 
 


conditional judgment of If + where
such a combination can cause an error when the condition in the where has more than the IF tag used. We take the query in 3.1 as an example, when the Java code is called as follows:

@Test public 
void Select_test_2_1 () { 
 studententity entity = new studententity (); 
 Entity.setstudentname (null); 
 Entity.setstudentsex (1); 
 list<studententity> list = this.dynamicSqlMapper.getStudentList_if (entity); 
 for (studententity e:list) { 
  System.out.println (e.tostring ()); 
 } 
} 

If the above example, the parameter studentname is null, the Student_name column will not be judged, it will directly guide the "WHERE and" keyword redundant error SQL.

We can then use the where dynamic statement to resolve. The "where" tag will know that if it contains a return value in the tag, it inserts a ' where '. In addition, if the label returns content that starts with and or or, it is removed.
The above example is modified to read:

<!--3 select-where/if (judgment parameter)-attributes that are not empty entity classes as where conditions--> <select id= "Getstudentlist_whereif" resultmap= Ap_studententity "parametertype=" liming.student.manager.data.model.StudentEntity "> select ST." student_id, ST. Student_name, ST. Student_sex, ST. Student_birthday, ST. Student_photo, ST. class_id, ST. place_id from Student_tbl St <where> <if test= "Studentname!=null" > St. Student_name like CONCAT (CONCAT ('% ', #{studentname, Jdbctype=varchar}), '% ') </if> <if test= ' studentsex!= n Ull and Studentsex!= ' "> ST. Student_sex = #{studentsex, jdbctype=integer} </if> <if test= "studentbirthday!= null" > and ST.  
   Student_birthday = #{studentbirthday, jdbctype=date} </if> <if test= "classId!= null and classid!=" "> and ST. class_id = #{classid, Jdbctype=varchar} </if> <if test= "classentity!= null and Classentity.classid!=null and Classentity.classiD!= ' "> ST.  
   class_id = #{classentity.classid, Jdbctype=varchar} </if> <if test= "Placeid!= null and Placeid!=" "> and ST.  place_id = #{placeid, Jdbctype=varchar} </if> <if test= "placeentity!= null and Placeentity.placeid null and Placeentity.placeid!= ' "> ST. place_id = #{placeentity.placeid, Jdbctype=varchar} </if> <if test= "StudentID!= null and StudentID!=" " > ST. 
 student_id = #{studentid, Jdbctype=varchar} </if> </where> </select>

if + Set UPDATE statement
when an if label is not used in an UPDATE statement, an error is caused if one of the arguments is null.
when the IF tag is used in an UPDATE statement, if the preceding if is not executed, or a comma-redundant error is caused. Use the set label to dynamically configure the Set keyword and to remove any unrelated commas appended to the end of the condition.
 
, when modified with the If+set label, does not update if an item is NULL, but instead maintains the database's original value. The following example:

<!--4 If/set (judgment parameters)-Update--> <update id= "Updatestudent_if_set" parametertype= "entity class is not empty" Liming.student.manager.data.model.StudentEntity "> UPDATE student_tbl <set> <if test=" Studentname!= nul L and Studentname!= ' "> Student_tbl. Student_name = #{studentname}, </if> <if test= "studentsex!= null and Studentsex!=" "> Student_tb L.student_sex = #{studentsex}, </if> <if test= "studentbirthday!= null" > Student_tbl. Student_birthday = #{studentbirthday}, </if> <if test= "Studentphoto!= null" > Student_tbl. Student_photo = #{studentphoto, javatype=byte[], Jdbctype=blob, Typehandler=org.apache.ibatis.type.blobtypehandler} , </if> <if test= "classId!=" "> Student_tbl. class_id = #{classid} </if> <if test= "Placeid!=" "> Student_tbl. place_id = #{placeid} </if> </set> WHERE student_tbl.  
student_id = #{studentid}; </update>
 

if + trim instead of the Where/set label
       Trim is more flexible to place the label for extra keywords, He can practice where and set effects.
 
Trim instead of where

<!--5.1 If/trim instead of where (judging parameters)-an attribute with an entity class that is not empty as a where condition--> <select id= "Getstudentlist_if_trim" Resultmap_studententity "> select ST. student_id, ST. Student_name, ST. Student_sex, ST. Student_birthday, ST. Student_photo, ST. class_id, ST. place_id from Student_tbl ST <trim prefix= "WHERE" prefixoverrides= "And|or" > <if test= "Studentname!=null "> ST. Student_name like CONCAT (CONCAT ('% ', #{studentname, Jdbctype=varchar}), '% ') </if> <if test= ' studentsex!= n Ull and Studentsex!= ' "> ST. Student_sex = #{studentsex, jdbctype=integer} </if> <if test= "studentbirthday!= null" > and ST.  
   Student_birthday = #{studentbirthday, jdbctype=date} </if> <if test= "classId!= null and classid!=" "> and ST. class_id = #{classid, Jdbctype=varchar} </if> <if test= "classentity!= null and Classentity.classid!=null and Classentity.classid!= ' "> ST. Class_id = #{classentity.classid, Jdbctype=varchar} </if> <if test= "Placeid!= null and Placeid!=" "> and ST.  place_id = #{placeid, Jdbctype=varchar} </if> <if test= "placeentity!= null and Placeentity.placeid null and Placeentity.placeid!= ' "> ST. place_id = #{placeentity.placeid, Jdbctype=varchar} </if> <if test= "StudentID!= null and StudentID!=" " > ST. 
 student_id = #{studentid, Jdbctype=varchar} </if> </trim> </select>

 
trim instead of set

<!--5.2 If/trim instead of set (judging parameters)-Update--> <update id= "Updatestudent_if_trim" with attributes that are not empty for entity classes Liming.student.manager.data.model.StudentEntity "> UPDATE student_tbl <trim prefix=" SET "suffixoverrides=", " > <if test= "studentname!= null and Studentname!=" "> Student_tbl. Student_name = #{studentname}, </if> <if test= "studentsex!= null and Studentsex!=" "> Student_tb L.student_sex = #{studentsex}, </if> <if test= "studentbirthday!= null" > Student_tbl. Student_birthday = #{studentbirthday}, </if> <if test= "Studentphoto!= null" > Student_tbl. Student_photo = #{studentphoto, javatype=byte[], Jdbctype=blob, Typehandler=org.apache.ibatis.type.blobtypehandler} , </if> <if test= "classId!=" "> Student_tbl. class_id = #{classid}, </if> <if test= "Placeid!=" "> Student_tbl. place_id = #{placeid} </if> </trim> WHERE student_tbl.student_id = #{studentid} </update> 
 

Choose (when, otherwise)
 
Sometimes we don't want to apply all the criteria, but just want to select one from multiple options. When using the If label, the condition in the If label is executed as long as the expression in test is true. MyBatis provides a choose element. The IF tag is a relationship to (and), and choose is a relationship to or (or) than a proud day. The
Choose tag is in order to determine whether the test condition in its internal when label is set, and if one is established, the Choose ends. When all conditions in the Choose are dissatisfied, the SQL in otherwise is executed. A Java-like switch statement, choose Switch,when to Case,otherwise is default.
For example, the following example, all the conditions can be limited to write, the use of aspects. Choose from top to bottom choose SQL Execution with test true for the When label. Security considerations, we use where to wrap the Choose, placing more keywords than errors.

<!--6 Choose (judging parameters)-sequentially--> the entity class with the first Non-empty property as where condition <select id= "Getstudentlist_choose" resultmap= Studententity "parametertype=" liming.student.manager.data.model.StudentEntity "> select ST." student_id, ST. Student_name, ST. Student_sex, ST. Student_birthday, ST. Student_photo, ST. class_id, ST. place_id from Student_tbl St <where> <choose> <when test= "Studentname!=null" > St. Student_name like CONCAT (CONCAT ('% ', #{studentname, Jdbctype=varchar}), '% ') </when > <when test= ' StudentS Ex!= null and Studentsex!= ' "> ST.  Student_sex = #{studentsex, jdbctype=integer} </when > <when test= "studentbirthday!= null" > and St. Student_birthday = #{studentbirthday, jdbctype=date} </when > <when test= "classId!= null and classid!=" "> ST. class_id = #{classid, Jdbctype=varchar} </when > <when test= "classentity!= null and CLAssentity.classid!=null and Classentity.classid!= ' "> ST. class_id = #{classentity.classid, Jdbctype=varchar} </when > <when test= "Placeid!= null and PlaceId!= ' "> ST. place_id = #{placeid, Jdbctype=varchar} </when > <when test= "placeentity!= null and Placeentity.placeid != null and Placeentity.placeid!= ' "> ST. place_id = #{placeentity.placeid, Jdbctype=varchar} </when > <when test= "StudentID!= null and StudentId != ' "> ST. student_id = #{studentid, Jdbctype=varchar} </when > <otherwise> </otherwise> </choose 
 > </where> </select>


foreach
for dynamic SQL, it is imperative that the master iterate over a collection, usually in the in condition. The list instance uses "list" as the key, and the array instance is "array" as the key.
The foreach element is very powerful and allows you to specify a collection, declare the collection items, and index variables that can be used in an element's body. It also allows you to specify open and closed strings, and to place delimiters between iterations. This element is intelligent and does not accidentally append extra delimiters.
Note: You can pass a list instance or an array to MyBatis as a parameter object. When you do this, MyBatis automatically wraps 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.
This section is discussed with respect to XML configuration files and XML mapping files. The next section discusses the Java API in detail, so you can get the most efficient mapping you've created.

1. The parameter is the array example of the wording

method declaration of an interface:

Public list<studententity> Getstudentlistbyclassids_foreach_array (string[] classids); 


Dynamic SQL statement:

<!-7.1 foreach (loop array parameter)-as the condition in where--> 
<select id= "Getstudentlistbyclassids_foreach_array" resultmap= "Resultmap_studententity" > 
 SELECT ST. student_id, 
   ST. Student_name, 
   ST. Student_sex, 
   ST. Student_birthday, 
   ST. Student_photo, 
   ST. class_id, 
   ST. place_id from 
  Student_tbl St 
  WHERE St. class_id 
  in <foreach collection= "array" item= "ClassIDs" open= "(" separator= "," close= ")" > 
  #{classids } 
  </foreach> 
</select> 


Test code, query students, in 20000001, 20000002 of these two classes of students:

@Test public 
void Test7_foreach () { 
  string[] ClassIDs = {"20000001", "20000002"}; 
  list<studententity> list = This.dynamicSqlMapper.getStudentListByClassIds_foreach_array (classids); 
  for (studententity e:list) { 
    System.out.println (e.tostring ()); 
  } 
} 

2. The parameter is the list example of the wording
method declaration of an interface:

Public list<studententity> getstudentlistbyclassids_foreach_list (list<string> classIdList); 


Dynamic SQL statement:

<!--7.2 foreach (cyclic list<string> parameters)-as in where conditions--> 
<select id= "Getstudentlistbyclassids_ Foreach_list "resultmap=" resultmap_studententity "> 
 select ST." student_id, 
   ST. Student_name, 
   ST. Student_sex, 
   ST. Student_birthday, 
   ST. Student_photo, 
   ST. class_id, 
   ST. place_id from 
  Student_tbl St 
  WHERE St. class_id 
  in <foreach collection= "list" item= "Classidlist" open= "(" separator= "," close= ")" > 
  #{ Classidlist} 
  </foreach> 
</select> 


Test code, query students, in 20000001, 20000002 of these two classes of students:

@Test public 
void Test7_2_foreach () { 
 arraylist<string> classidlist = new arraylist<string> (); 
 Classidlist.add ("20000001"); 
 Classidlist.add ("20000002"); 
 list<studententity> list = This.dynamicSqlMapper.getStudentListByClassIds_foreach_list (classidlist); 
 for (studententity e:list) { 
  System.out.println (e.tostring ()); 
 } 
} 

3. Encapsulate the parameters into the type of map

<select id= "Dynamicforeach3test" resulttype= "Blog" > 
 select * from T_blog where title like "%" #{title} "%" and I D in 
 <foreach collection= "IDs" index= "index" item= "Item" open= "(" separator= "," close= ")" > 
  #{item} 
 </foreach> 
</select> 

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:

@Test public 
void Dynamicforeach3test () { 
 sqlsession session = Util.getsqlsessionfactory (). Opensession (); 
 Blogmapper blogmapper = Session.getmapper (blogmapper.class); 
 Final list<integer> ids = new arraylist<integer> (); 
 Ids.add (1); 
 Ids.add (2); 
 Ids.add (3); 
 Ids.add (6); 
 Ids.add (7); 
 Ids.add (9); 
 map<string, object> params = new hashmap<string, object> (); 
 Params.put ("IDs", IDs); 
 Params.put ("title", "China"); 
 list<blog> blogs = blogmapper.dynamicforeach3test (params); 
 for (blog blog:blogs) 
  System.out.println (blog); 
 Session.close (); 
} 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.