What is deferred loading?
Lazy loading is also called load-on-demand, which means loading the master information first, and then loading the information when needed.
Demand:
Query the order information, when necessary to query the user information
Implementation method:
Write two statement, one statement is to query the order information, one is to query the user information, but query the order Information statement to use the RESULTMAP tag for results mapping.
Mapper Interface:
/**
* Delay loading query When the order needs to query user information
* */
Public list<orderext> lazyloading ();
Mapper Map File: Ordermapper.xml
<resultmap type= "Orderext" id= "lazyloading" >
<!--order Information--
<id column= "id" property= "id"/>
<result column= "number" property= "number"/>
<result column= "user_id" property= "user_id"/>
<!--user Information--
<association property= "User"
select= "Com.heima.mapper.UserMapper.findUserById" column= "user_id"/>
</resultMap>
<!--delayed Load-
<select id= "lazyloading" resultmap= "lazyloading" >
SELECT * FROM Orders
</select>
<select id= "Finduserbyid" parametertype= "int" resulttype= "Com.heima.po.User" >
SELECT * FROM USER WHERE id = #{id}
</select>
MyBatis Global Map File:
<!--lazy Loading
<settings>
<setting name= "lazyloadingenabled" value= "true"/>
& Lt;setting name= "aggressivelazyloading" value= "false"/>
</settings>
test class:
@Test
public void lazyloading () {
sqlsession sqlsession = sqlsessionfactory.opensession ( );
ordermapper mapper = Sqlsession.getmapper (Ordermapper.class);
List<OrderExt> List = mapper.lazyloading ();
for (Orderext order:list) {
system.out.println (order);
}
An error occurred during the test:
Workaround:
The Ordermapper mapping file in the association label of the column value is wrong, the following is the correct wording, column this property can not be omitted, or will be an error.
<association property= "User"
select= "Com.heima.mapper.UserMapper.findUserById" column= "user_id"/>
Test mybatis delay Load errors and workarounds