Hibernate懒加载急加载我们需要注意的问题

本文介绍了Hibernate中的懒加载和急加载概念,并通过实例展示了@OneToMany和@ManyToOne注解下不同加载方式的行为。分析了1+N查询问题,提出了在一对多关系下避免N+1查询的优化策略,强调了合理使用关联查询和DTO对象的重要性。
摘要由CSDN通过智能技术生成

1、显而易见的概念

懒加载——也被称为延迟加载,它在查询的时候不会立刻访问数据库,而是返回代理对象,当真正去使用对象的时候才会访问数据库。

急加载——就是只要我们实体做了关联,全部一次性执行完所有的SQL语句

2、@OneToMany

  ****默认为懒加载****
     @Test
    public void find(){
        Session s=  sessionFactory.openSession();
        List<TeacherEntity> teacher=    s.createQuery("from  TeacherEntity").list();
          for(TeacherEntity t:teacher){
              t.getTname();
            List<StudentEntity> lists=  t.getStuList();
            for(StudentEntity stu:lists){
                System.out.println(stu.getSname());
            }
          } 
        s.close();  
    }

懒加载结果:

Hibernate: select teacherent0_.t_id as t_id1_5_, teacherent0_.t_name as t_name2_5_ from t_teacher2 teacherent0_

Hibernate: select stulist0_.tid as tid3_4_0_, stulist0_.s_id as s_id1_4_0_, stulist0_.s_id as s_id1_4_1_, stulist0_.s_name as s_name2_4_1_, stulist0_.tid as tid3_4_1_ from t_student2 stulist0_ where stulist0_.tid=? <

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值