MyBatis延迟加载

一、SqlMapConfig.xml中开启延迟加载

 <!-- 加载properties文件 -->
  <properties resource="db.properties"></properties>
 	
  <settings>
  	<setting name="lazyLoadingEnabled" value="true"/>
  	<setting name="aggressiveLazyLoading" value="false"/>
  </settings>

二、mapper.xml中配置如下

<resultMap type="com.leech.mybatis.first.pojo.Orders" id="OrdersUserLazyLoadingResultMap">
		<id property="id" column="id"/>
		<result property="userId" column="user_id"/>
		<result property="number" column="number"/>
		<result property="createtime" column="createtime"/>
		<result property="note" column="note"/>
		
		<!-- 延迟加载 -->
		<association property="user" javaType="com.leech.mybatis.first.pojo.User" select="com.leech.mybatis.first.mapper.UserMapper.findUserById" column="user_id">
			
		</association>
	</resultMap>
	
	<!-- select延迟加载 -->
	<select id="findOrdersUserLazyLoading" resultMap="OrdersUserLazyLoadingResultMap">
		select orders.* from orders
	</select>

三、pom.xml加入cglib依赖

<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2.2</version>
	</dependency>

四、测试用例

@Test
	public void testFindOrdersUserLazyLoading() throws Exception{
		SqlSession sqlSession = factory.openSession();
		OrdersCustomMapper ordersCustomMapper = sqlSession.getMapper(OrdersCustomMapper.class);
		List<Orders> list = ordersCustomMapper.findOrdersUserLazyLoading();
		for(Orders orders : list) {
			User u = orders.getUser();
			System.out.println(u);
		}
	}


你可能感兴趣的:(MyBatis延迟加载)