天天看点

MyBatis延迟加载及在spring中集成配置



当你要使用one to one,many to one 就会碰到n+1的问题。很明显,对象之间关联很多有a关联b,b关联c,c关联a这样的关系,如果不是采用延迟加载,很容易一下在出现成千上万对象,造成n+1的问题。

而mybatis 设置延迟加载主要2个属性配置:

<?xml version="1.0" encoding="utf-8"?>    

<!doctype configuration     

  public "-//ibatis.apache.org//dtd config 3.0//en" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">    

<configuration>  

    <settings>  

        <setting name="lazyloadingenabled" value="false"/>  

        <setting name="aggressivelazyloading" value="true"/>  

    </settings>  

</configuration>     

lazyloadingenabled:true使用延迟加载,false禁用延迟加载。默认为true

aggressivelazyloading:true启用时,当延迟加载开启时访问对象中一个懒对象属性时,将完全加载这个对象的所有懒对象属性。false,当延迟加载时,按需加载对象属性(即访问对象中一个懒对象属性,不会加载对象中其他的懒对象属性)。默认为true

   加载所有懒对象

        <setting name="lazyloadingenabled" value="true"/>  

</configuration>    

   按需加载对象属性

        <setting name="aggressivelazyloading" value="false"/>  

</configuration>   

对继承spring配置如下:

<bean id="sqlsessionfactory"  

    class="org.mybatis.spring.sqlsessionfactorybean">  

    <property name="configlocation" value="classpath:setting.xml"/>  

    <property name="datasource" ref="datasource" />  

</bean>  

setting.xml是mybatis全局属性配置文件。