前言
resultMap可以实现高级映射(使用association、collection实现一对一及一对多映射),association、collection具备延迟加载功能。
延迟加载:先从单表查询、需要时再从关联表去关联查询,大大提高数据库性能,因为查询单表要比关联查询多张表速度要快。
使用association实现延迟加载
mybatis默认没有开启延迟加载,需要在SqlMapConfig.xml中setting配置。
1 2 3 4 5 6 7 8
| <settings> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings>
|
1.只查询订单信息
1 2 3
| <select id="findOrdersUserLazyLoading" resultMap="OrdersUserLazyLoadingResultMap"> SELECT * FROM orders </select>1234
|
2.关联查询用户信息
1 2 3
| <select id="findUserById" parameterType="int" resultType="com.iot.mybatis.po.User"> SELECT * FROM user WHERE id=#{value} </select>
|
上边先去执行findOrdersUserLazyLoading,当需要去查询用户的时候再去执行findUserById,通过resultMap的定义将延迟加载执行配置起来。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <resultMap type="com.iot.mybatis.po.Orders" id="OrdersUserLazyLoadingResultMap"> <id column="id" property="id"/> <result column="user_id" property="userId"/> <result column="number" property="number"/> <result column="createtime" property="createtime"/> <result column="note" property="note"/>
<association property="user" javaType="com.iot.mybatis.po.User" select="com.iot.mybatis.mapper.UserMapper.findUserById" column="user_id">
</association>
</resultMap>
|
mapper.java
1 2
| public List<Orders> findOrdersUserLazyLoading()throws Exception;
|
Order类里封装User信息。
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Test public void testFindOrdersUserLazyLoading() throws Exception { SqlSession sqlSession = sqlSessionFactory.openSession(); OrdersMapperCustom ordersMapperCustom = sqlSession .getMapper(OrdersMapperCustom.class); List<Orders> list = ordersMapperCustom.findOrdersUserLazyLoading();
for (Orders orders : list) { User user = orders.getUser(); System.out.println(user); } }
|