2018-06-27 10:26:15 500浏览
lazy策略原理:只有在使用查询sql返回的数据是才真正发出sql语句到数据库,否则不发出(主要用在多表的联合查询)
<settings> <settingname="lazyLoadingEnabled"value="true"/> <settingname="aggressiveLazyLoading"value="false"/> </settings>
<selectid="findCid"parameterType="int"resultType="card"> select*fromcardwherecid=#{value}
</select>
<resultMaptype="person"id="p_c1">
<idcolumn="pid"property="pid"/>
<resultcolumn="pname"property="pname"/>
<resultcolumn="page"property="page"/>
<resultcolumn="psex"property="psex"/>
<associationproperty="card"javaType="card"select="findCid"
column="cid">
</association>
</resultMap>
<selectid="selectpersonAndCardLazyByPid"parameterType="int"
resultMap="p_c1">
SELECT*FROMpersonwherepid=#{value}
</select>
publicPersonselectpersonAndCardLazyByPid(intpid);
@Test
publicvoidtestselectpersonAndCardLazyByPid(){//lazy策略一对1
Personp=pm.selectpersonAndCardLazyByPid(1);
//System.out.println(p);
System.out.println(p.getPname()+",");
//System.out.println(p.getPname()+","+p.getCard().getCnum());
}
@Test
publicvoidtestselectpersonAndCardLazyByPid(){//lazy策略一对1
Personp=pm.selectpersonAndCardLazyByPid(1);
//System.out.println(p);
System.out.println(p.getPname()+",");
System.out.println(p.getPname()+","+p.getCard().getCnum());//当前台使用身份证号时才发出对card的查询
}
<!--lazy策略一对多-->
<selectid="fingCard_Adder"parameterType="int"resultType="adder">
select*fromadderwherepid=#{value}
</select>
<selectid="findCid1"parameterType="int"resultType="card">
select*fromcardwherecid=#{value}
</select>
<resultMaptype="person"id="p_c1_a1">
<idcolumn="pid"property="pid"/>
<resultcolumn="pname"property="pname"/>
<resultcolumn="page"property="page"/>
<resultcolumn="psex"property="psex"/>
<associationproperty="card"javaType="card"select="findCid1"
column="cid">
</association>
<collectionproperty="adder"ofType="Adder"select="fingCard_Adder"
column="pid">
</collection>
</resultMap>
<selectid="selectpersonAndCardAndAdderLazyByPid"parameterType="int"
resultMap="p_c1_a1">
SELECT*FROMpersonwherepid=#{value}
</select>
@Test
publicvoidtestselectpersonAndCardAndAdderLazyByPid(){//lazy策略一对多
Personp=pm.selectpersonAndCardAndAdderLazyByPid(1);
System.out.println(p.getPname()+",");////此处是只发出person信息的查询
}
@Test
publicvoidtestselectpersonAndCardAndAdderLazyByPid(){//lazy策略一对多
Personp=pm.selectpersonAndCardAndAdderLazyByPid(1);
System.out.println(p.getPname()+",");//此处是只发出person信息的查询;
System.out.println(p.getPname()+","+p.getCard().getCnum());//此处是发出person信息和身份信息的查询;
}
@Test
publicvoidtestselectpersonAndCardAndAdderLazyByPid(){//lazy策略一对多
Personp=pm.selectpersonAndCardAndAdderLazyByPid(1);
System.out.println(p.getPname()+",");//此处是只发出person信息的查询;
System.out.println(p.getPname()+","+p.getCard().getCnum());//此处是发出person信息和身份信息的查询;
//System.out.println(p.getPname()+","+p.getCard().getCnum());
for(Adderadder:p.getAdder()){////此处发出person信息和身份信息,地址信息的查询;
System.out.println(adder.getAshi());
}
}
以上所述是大家介绍的mybatis中延迟加载Lazy策略的方法,希望对大家有所帮助,如果对java感兴趣的话,或者想了解更多的java资讯的话,请登录扣丁学堂官网或关注微信公众号,更有大量java在线视频教程来观看。
【关注微信公众号获取更多学习资料】