mybatis中的懒加载

知识点:mybatis中的懒加载的使用

参考:https://www.cnblogs.com/ysocean/p/7336945.html?utm_source=debugrun&utm_medium=referral

(1)什么是mybatis的懒加载

        通俗的讲就是按需加载,我们需要什么的时候再去进行什么操作。而且先从单表查询,需要时再从关联表去关联查询,能大大提高数据库性能,

  因为查询单表要比关联查询多张表速度要快。

        在mybatis中,resultMap可以实现高级映射(使用association、collection实现一对一及一对多映射),association、collection具备延迟加载功能。

(2)使用实例

  mapper.xml文件

<mapper namespace="com.agesun.attendance.privilege.provider.mapper.OrgMapper">
<resultMap id="BaseResultMap" type="com.agesun.attendance.privilege.provider.model.Org">
<id column="org_id" jdbcType="INTEGER" property="orgId" />
<result column="parent_id" jdbcType="INTEGER" property="parentId" />
<result column="org_name" jdbcType="VARCHAR" property="orgName" />
<result column="state" jdbcType="INTEGER" property="state" />
<result column="orgFullName" jdbcType="VARCHAR" property="orgFullName" />
<collection property="psList" column="org_id" fetchType="lazy" select="com.agesun.attendance.privilege.provider.mapper.PersonMapper.selectByOrgId">
</collection> //单个resultMap中的懒加载设置 lazy为懒加载,不调用(get()),不从数据查询
</resultMap> eager急加载,查询主表时,就把子集合查询出来
</mapper>

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

在mybatis配置文件 mybatis-configuration.xml中,配置懒加载

<!-- 开启懒加载配置 -->
<settings>
    <!-- 全局性设置懒加载。如果设为‘false',则所有相关联的都会被初始化加载。 -->   //可以配置lazyLoadingEnabled 值为true,不设置aggressiveLazyLoading,为全局设置
<setting name="lazyLoadingEnabled" value="true"/>
 <!-- 当设置为‘true'的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。 -->
    <setting name="aggressiveLazyLoading" value="false"/>
</settings>
 



猜你喜欢

转载自www.cnblogs.com/shuaifing/p/9230976.html
今日推荐