"MyBatis Framework" advanced mapping-lazy loading

Source: Internet
Author: User

Lazy Loading
1. What is deferred loading

Resultmap can implement advanced Mapping (using association, collection for one-to-one and one-to-many mappings), association and collection have lazy loading capabilities.
Demand:
Queries the user information if the order is queried and associated. If you query the order information to meet the requirements, when we need to query user information and then query user information. The on-demand query of user information is deferred loading.

Lazy Loading: The database performance is greatly improved by querying from a single-table query, when needed, and then from related tables, because it is faster to query a single table than to query multiple tables.

2. Using Association for Lazy loading

2.1 Requirements
Querying orders and correlating query user information

2.2mapper.xml

You need to define a method corresponding to the mapper of two statement.
(1) Check order information only
SELECT * FROM Orders

<!--query orders, associated query users, user information needs to delay loading--<select id= "findordersuserlazyloading" resultmap= " Ordersuserlazyloadingresultmap "> select * from Orders </select>

Use Association to delay loading (executing) satatement (correlate query user information) in statement of the query order

(2) Related query user information
Query user information by USER_ID in the order information above

<!--lazy loading using SQL--<select id= "Finduserbyid" parametertype= "int" resulttype= "Cn.edu.hpu.mybatis.PO.User" &      Gt SELECT * from USER WHERE Id=#{id} </select>

On the top of the first to execute the findordersuserlazyloading, when the need to query the user's time to execute the Finduserbyid, through the RESULTMAP definition of deferred load execution configuration.

2.3 Lazy Load Resultmap
Use the Select in association to specify the ID of the statement to be executed for lazy loading.

    <!--  Deferred load Resultmap -->     <resultmap  id= "Ordersuserlazyloadingresultmap"  type= "Cn.edu.hpu.mybatis.PO.Orders" >          <!--  Map Configuration of order information  -->              <id column= "id"  property= "id"/>             <result column= "user_id"  property= "UserId"/>             <result column= "Number"   property= "Number"/>            <result  Column= "Creattime"  property= "Creattime"/>             <result column= "Note"  property= "note"/>                   <!--  Enable lazy loading of user information            select: Specifies the SQL statement that is required to execute for lazy loading, that is, a select tag in the mapper.xml configuration file pair           column: The column in the Order information query for the associated user information is user_id.           Associated SQL is understood as:          SELECT orders.*,         (select username  From user where orders.user_id=user.id) username,          (select sex from user where orders.user_id=user.id) sex         FROM orders;-->         < association property= "User"  javatype= "cn.edu.hpu.mybatis.PO.User"  select= "Finduserbyid"   Column= "user_id" >                      </association>       </resultMap>

2.4mapper.java

Package Cn.edu.hpu.mybatis.mapper;import Java.util.list;import Cn.edu.hpu.mybatis.po.orders;import Cn.edu.hpu.mybatis.po.orderscustom;import cn.edu.hpu.mybatis.po.user;//Order Mapperpublic Interface Orderscustommapper {//...//Query Order association query user, where user information is delayed loading public list<orders> findordersuserlazyloading () thr oWS Exception;}

2.5 Testing
2.5.1 Test Ideas:
1, execute the top mapper method (findordersuserlazyloading), internal to call The findordersuserlazyloading in Cn.itcast.mybatis.mapper.OrdersMapperCustom only queries the orders information (single table).

2, in the program to traverse the previous step to query out the LIST&LT;ORDERS&GT, when we call the GetUser method in Orders, we begin to delay loading.

3, delay loading, to call Usermapper.xml in Finduserbyid this method to obtain user information.

2.5.2 Deferred load configuration
MyBatis does not turn on lazy loading by default and needs to be setting configured in Sqlmapconfig.xml.

Configure in the MyBatis core configuration file:
L azyloadingenabled, aggressivelazyloading
Set Item description allowable value default value
lazyloadingenabled Global Settings lazy loading. If set to ' false ', all associated will be initialized to load. true | FalseFalse
Aggressivelazyloading When set to ' true ', lazy-loaded objects may be loaded by any lazy property. Otherwise, each property is loaded on demand. true | FalseTrue

Configure in Sqlmapconfig.xml:

<configuration> ... <!--settings--> <settings> <!--turn on the delay-loaded switch-- <setting name= "lazyloadingenable" value= "true"/> <!--positive load changed to negative load (and load on demand)--<setting name = "Aggressivelazyloading" value= "false"/> </settings> ......</configuration>

2.5.3 Test Code
Query order associated user information, user information implementation delay loading

@Test     public void testfindorderuserlazyloading ()  throws exception{                 sqlsession  sqlsession=sqlsessionfactory.opensession ();         //Create a proxy object         orderscustommapper ordersmappercustom= Sqlsession.getmapper (Orderscustommapper.class);                 //method of calling Mapper         List< Orders> ods=ordersmappercustom.findordersuserlazyloading ();                 for  (int i = 0; i <  ods.size ();  i++)  {             Orders od=ods.get (i);            //execution GetUser to query user information, here to implement the delay load              user user=od.getuser ();             system.out.println ("User name:" +user.getusername ());         }    }

Output Results and log information:

debug [main] - opening jdbc connection  debug [main] -  created connection 29706134.  debug [main] - setting autocommit  To false on jdbc connection [[email protected]]  debug [main]  - ==>  preparing: select * from orders   debug  [main] - ==> Parameters:   DEBUG [main] - <==       Total: 3  DEBUG [main] - ==>   Preparing: select * from user where id=?   debug [main]  - ==> parameters: 1 (Integer)   DEBUG [main] - <==       Total: 1   user name: Zhang San    user name: Zhang San   debug [main]  - ==>  preparing:&nBsp Select * from user where id=?   debug [main] - ==>  parameters: 3 (Integer)   DEBUG [main] - <==       Total: 1   User name: Liu

2.6 Deferred Load thinking
How to implement lazy loading without using the lazy load feature in the association and collection provided by MyBatis??

The implementation method is as follows:
Define two mapper methods:
1. Inquiry Order List
2. Query user information according to user ID
Implementation ideas:
To query the first mapper method, get the Order information list
In the program (service), on demand to call the second Mapper method to query user information.

Anyway:

Using lazy Load method, the first query simple SQL (preferably a single table, you can also associate the query), and then to load the additional information associated with the query.

"MyBatis Framework" advanced mapping-lazy loading

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.