About ibatis batch-How far can we go series (26)

Source: Internet
Author: User
How far can we go series (26)

Recommended:

We recommend that you use Evernote or other similar tools to browse the Web page. Currently, most of our reading is implemented through the real screen as a window, it is necessary to take notes or try again, especially for those technicalArticleWhen Evernote was recently used, it was found very good. You can install a plug-in the browser. When you encounter a good article, you can easily record it and synchronize it to your mobile device, evernote is not free offline. If you don't want to use traffic, you can open those articles on WiFi and close them after loading. You can go home at night to view them offline!

Subject:

Record some basic things:

1. in Java, the list duration deletion problem is as follows:

SimplifiedFor-eachA loop is just a syntactic sugar, which is equivalent to the following:Code:

For(Iterator <comtype> iter =Comlist. iterator (); ITER. hasnext ();) {comtype com=ITER. Next ();If(! Com. getname (). Contains ("ABC") {Comlist. Remove (COM );}}

However, it is not supported to traverse and delete a special list at the same time.

Solution:

UseIteratorTraverse, useIterator. Remove () Delete the elements you want to delete.

 

 
For(Iterator <comtype> iter =Comlist. iterator (); ITER. hasnext ();) {comtype com=ITER. Next ();If(! Com. getname (). Contains ("ABC") {ITER. Remove ();}}

2. Map Traversal

Negative textbook code:

 
For(Long ID: useralbummap. keyset ()){If(Useralbummap. Get (ID)> 0){//Traverse the mapUserandjourneydo userandjourney= Usermap. Get (ID); userandjourney. setalbum (1);}}

Pay attention to the comments section. I think the above Code traverses the map at least twice.

Improvement:

For(Map. Entry <long, integer>Entry: useralbummap. entryset ()){If(Entry. getvalue ()> 0 ){//Ready for use, no need to traverse MapUserandjourneydo userandjourney =Usermap. Get (entry. getkey (); userandjourney. setalbum (1);}}

 

3. ibatis Batch Processing

The problem is: To improve execution efficiency, we need to do a lot of things at one time when establishing a connection with the database.

Why? Just imagine that if the database is deployed in a distributed manner, a socket should be set up for each connection, and this overhead will be high.

For example, when I query data based on multiple user IDs, we consider using SQL in syntax to retrieve all the information to be queried.

Loop usage in ibatis:

     < Select  ID  = "Select_profile_by_uids"  Parameterclass  = "Java. util. List"  Resultmap  = "Userprofileresult"  >  Select * From tb_user_profile where user_id in  <  Iterate  Open  = "("  Close  = ")" Conjunction  = ","  > # Userids [] # </  Iterate  >      </  Select  > 

SQL syntax can solve some problems.

Look at a single insert:

 
PublicLong addalbum (albumdo album ){Return(Long)This. Getsqlmapclienttemplate (). insert ("insert_album", Album );}

Sqlmap:

    <  Insert  ID  = "Insert_album"  Parameterclass  = "Album"  >  Insert into tb_user_album (user_id, URL, status, create_time, edit_time) values (# userid #, # URL #, # status #, now (), now ())  <  Selectkey  Resultclass  = "Java. Lang. Long"  Keyproperty  = "ID" >  Select last_insert_id () as ID  </  Selectkey  >      </  Insert  > 

Change to batch insert: Use sping,Note that the input parameters must be final modified.

     Public   Void Batchaddalbum ( Final List <albumdo> List ){  If (List! = Null ){  This .Getsqlmapclienttemplate(cmd.exe cute ( New  Sqlmapclientcallback () {@ override  Public  Object doinsqlmapclient (sqlmapexecutor executor)  Throws  Sqlexception {executor. startbatch ();  For ( Int I = 0, n = List. Size (); I <n; I ++ ) {Executor. insert ( "Insert_album" , List. Get (I);} executor.exe cutebatch ();  Return   Null  ;}});}} 

We recommend that you take a look at the source code of org. springframework. Orm. ibatis. sqlmapclienttemplate, which is easier to understand.

 

4. About spring manual transaction control

Although it is recommended to configure and control transactions, sometimes there are several abnormal requirements or scenarios that need to be manually controlled and spring is used.

The code model is as follows:

 //  Start transaction Defaulttransactiondefinition def = New Defaulttransactiondefinition (); def. setpropagationbehavior (transactiondefinition. propagation_requires_new); transactionstatus status = Transactionmanager. gettransaction (DEF ); //  Obtain the Transaction Status          Boolean Rollbackflg = True  ;  Try  {  //  Database processing 1  //  Database processing 2 Transactionmanager. Commit (Status );  //  Submit Rollbackflg = False ; //  Tag bit  }}  Catch  (Exception e) {logger. Error ( "Insert table error:" + E );  //  Roll back a transaction  Transactionmanager. rollback (Status); rollbackflg = True  ;}  Finally  {}  //  Data rollback          If  (Rollbackflg ){}  Else  {} 

 

 

Let's move on

----------------------------------------------------------------------

Hard work may fail, but not hard work will certainly fail.
Mutual encouragement.

Related Article

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.