MyBatis Implementing Batch Updates

Source: Internet
Author: User

Update a single record

1 UPDATE Course SET name = ' COURSE1 ' WHERE id = ' ID1 ';

update multiple records with the same field value

1 UPDATE Course SET name = ' course1 ' WHERE ID in (' id1 ', ' id2 ', ' id3 ');   

Update multiple records to different values for multiple fields

The more common notation is to execute the UPDATE statement in turn, by looping.

MyBatis the following:

123456789 <update id= "UpdateBatch" parametertype= "java.util.List" > <foreach collection= "List" item= "item" index= "Inde X "open=" "close=" "separator="; "     > Update course <set> name=${item.name} </set> where id = ${item.id} </foreach> </update>

One record update once, poor performance, easy to cause congestion.

MySQL does not provide a straightforward way to implement bulk updates, but it can be implemented using case-when syntax.

123456789101112< /td> update course    set  name = case id         when 1 then   ' name1 '         WHEN 2 THEN  ' name2 '          WHEN 3 THEN  ' Name3 '     END,      title = case id         when  1 THEN  ' new title 1 '         when 2  THEN  ' new title 2 '         when 3 then   ' new title 3 '     ENDWHERE id IN  (+/-)

This SQL means that if the ID is 1, the value of name Name1,title is new Title1, and so on.

The configuration in MyBatis is as follows:

1234567891011121314151617181920212223242526272829303132333435363738 <update id= "UpdateBatch"  parametertype= "list" >             update course             <trim prefix= "Set"  suffixoverrides= "," >              <trim prefix= "Peopleid =case"  suffix= "End," >                  <foreach  collection= "List"  item= "I"  index= "index" >                          <if  Test= "I.peopleid!=null" >                           when id=#{i.id} then  #{i.peopleid}                          </if>                  </foreach>               </trim>               <trim prefix= " roadgridid =case"  suffix= "End," >                  <foreach  collection= "List"  item= "I"  index= "index" >                          <if  Test= "I.roadgridid!=null" >                           when id=#{i.id} then #{i.roadgridid}                           </if>                  </foreach>               </trim>                             <trim  prefix= "Type =case"  suffix= "End,"  >                  <foreach collection= "List"  item= "I"   index= "Index" >                     &nbSp;    <if test= "I.type!=null" >                            when id=#{i.id} then #{i.type}                          </if>                  </foreach >              </trim>        <trim prefix= "Unitsid =case"  suffix= "End,"  >                    <foreach collection= "List"  item= "I"  index= "index" >            &nbsP;              <if test= " I.unitsid!=null ">                            when id=#{i.id} then #{ i.unitsid}                           </if>                   </foreach>            </trim>              </trim>             where            <foreach collection = "List"  separator= "or"  item= "I"  index= "index"  >               id=#{i.id}          </foreach></ Update>

Note:

MyBatis's foreach statement foreachis used primarily 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:
    1. If a single parameter is passed in and the parameter type is a list, the collection property value is List
    2. If a single parameter is passed in and the parameter type is an array, the value of the collection property is array
    3. If the parameters passed in are multiple, we need to encapsulate them into a map, of course, the single parameter can also be encapsulated asa map, in fact, if you pass in the parameter, in the breast 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 are the sample code for each of the three cases: 1. The type of the single parameter list:
<select id= "Dynamicforeachtest" resulttype= "Blog" >
SELECT * from T_blog where ID in
<foreach collection= "list" index= "index" item= "Item" open= "(" separator= "," close= ")" >
#{item}
</foreach>
</select>
The value of the above collection is list, the corresponding Mapper is this
Public list<blog> dynamicforeachtest (list<integer> IDs);
Test code:
@Test
public void Dynamicforeachtest () {
sqlsession session = Util.getsqlsessionfactory (). Opensession ();
Blogmapper blogmapper = Session.getmapper (Blogmapper.class);
list<integer> ids = new arraylist<integer> ();
Ids.add (1);
Ids.add (3);
Ids.add (6);
list<blog> blogs = blogmapper.dynamicforeachtest (IDS);
for (Blog blog:blogs)
SYSTEM.OUT.PRINTLN (blog);
Session.close ();
}
2. Type of single-parameter array arrays:
<select id= "Dynamicforeach2test" resulttype= "Blog" >
SELECT * from T_blog where ID in
<foreach collection= "Array" index= "index" item= "Item" open= "(" separator= "," close= ")" >
#{item}
</foreach>
</select>
The above collection is an array, corresponding to the mapper code:
Public list<blog> dynamicforeach2test (int[] IDs);
The corresponding test code:
@Test
public 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
<select id= "Dynamicforeach3test" resulttype= "Blog" >
SELECT * from T_blog where title like "%" #{title} "%" and ID 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 ();
}

MyBatis Implementing Batch Updates

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.