数据库查询n+1问题

14 篇文章 0 订阅
7 篇文章 0 订阅

数据库查询n+1问题

原文地址 https://blog.csdn.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 带来的性能问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值