知識點: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>