数据库查询n+1问题
数据库查询n+1问题
原文地址 https://blog.****.net/wangjun5159/article/details/52389480
简介
在 orm 框架中,比如 hibernate 和 mybatis 都可以设置关联对象,比如 user 对象关联 dept
假如查询出 n 个 user,那么需要做 n 次查询 dept,查询 user 是一次 select,查询 user 关联的
dept,是 n 次,所以是 n+1 问题,其实叫 1+n 更为合理一些。
mybatis 配置
UserMapper.xml
<resultMap id="BaseResultMap" type="testmaven.entity.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="dept_id" jdbcType="INTEGER" property="deptId" />
<association property="dept" column="dept_id" fetchType="eager" select="testmaven.mapper.DeptMapper.selectByPrimaryKey" ></association>
</resultMap>
DeptMapper.xml
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from dept
where id = #{id,jdbcType=INTEGER}
</select>
我们可以看到 user 通过 association 中的 dept_id 关联了 dept,查询 user 后,比如查询到 4 个 user,那么会执行 4 次查询 dept;
测试
List<User> list = userMapper.selectByExample(null);
打印 jdbc log 我们能看到,查询到 4 个 user,然后执行了 4 次查询 dept
1+n 带来的问题
查询主数据,是 1 次查询,查询出 n 条记录;根据这 n 条主记录,查询从记录,共需要 n 次,所以叫数据库 1+n 问题;这样会带来性能问题,比如,查询到的 n 条记录,我可能只用到其中 1 条,但是也执行了 n 次从记录查询,这是不合理的。为了解决这个问题,出现了懒加载,懒加载就是用到的时候再查询;我们设置 association 元素中的 fetchType fetchType=lazy
<association property="dept" column="dept_id" fetchType="lazy" select="testmaven.mapper.DeptMapper.selectByPrimaryKey" ></association>
我们再做测试
List<User> list = userMapper.selectByExample(null);
User u = list.get(0);
System.out.println(u.getClass());
System.out.println(u.getName());
jdbc log
懒加载 减少了性能消耗,一定程度上缓解了 1+n 带来的性能问题
总结
1+n 问题是什么?应该怎样解决?
- 1+n 是执行一次查询获取 n 条主数据后,由于关联引起的执行 n 次查询从数据;它带来了性能问题;
- 一般来说,通过懒加载 可以部分缓解 1+n 带来的性能问题