The use of collections in the XML configuration of MyBatis is mainly the use of foreach dynamic statements.
Parameters for foreach:
The properties of the Foreach element are mainly item,index,collection,open,separator,close.
Item represents the alias at which each element in the collection iterates.
index specifies a name that is used to indicate where each iteration takes place during the iteration.
Open indicates what the statement begins with, and separator represents what symbol is used as the delimiter between each iteration.
Close indicates what ends with.
1. MyBatis generate a query for the SELECT * from table where ID in (,..., N) statement
It is common practice to specify the name of the passed parameter at the parameter of the method, and when used in XML, the name of the collection is the same as the name of the method's param, so it is easy to read and understand, and then the Foreach loop is used in the corresponding XML file.
The Java code is as follows:
PublicAbstractList<Model> findbyids(@Param("IDs") List<Integer> IDs);
The corresponding XML code is as follows:
Select* from Table<where> ID in <foreach collection= "IDs" Item= "item" = "index" Open= ( " Separator= Close= >#{item}</></where >
2.Mybatis Save multiple records
We are also using the Foreach method, where we use the syntax rules of SQL to deal with MyBatis's foreach dynamic statement.
Java code:
Publicabstractvoid saves(@Param("Tables")List<Model > tables);
XML code:
INSERT INTO table (name,addtime Values<foreach collection= "tables" Item= "item" = "index" Separator= > (#{itemname},#{item. Addtime</foreach >
The above method MyBatis will help us with SQL injection interception, MyBatis if the #{xxx} to set parameters, MyBatis SQL injection filtering. If the ${xxx},mybatis is not SQL injection filtering, the contents of the input are directly output as SQL statements.
Determine whether a collection has values
<ifTest="List!=null and List.size () >0" ></if>
MyBatis working with statements such as collections, loops, arrays, and in queries