数据库查询的N+1问题

转载自:https://blog.csdn.net/w05980598/article/details/79647291

简介

在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带来的性能问题

猜你喜欢

转载自blog.csdn.net/harryptter/article/details/85375933
今日推荐