hibernate sql太多了

时间:2014-04-08 04:18:10

标签: sql hibernate

我有test1类和test2类

它们是一对一的,而获取类型是懒惰的。

@Entity
@Table(name = "test1")
public class Test1 {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private int id;

    @Column(name="name")
    private String name;

    @OneToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name = "test2_id")
    private Test2 test2;

    ...
}

@Entity
@Table(name = "test2")
public class Test2 {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private int id;

    @Column(name="name")
    private String name;

    @OneToOne(mappedBy = "test2")

    ...

}

我想从数据库中获取所有记录:

    Criteria dc2 =
    sessionFactory. getCurrentSession().createCriteria(Test1.class,"mr");
    List<Test1> reports2= dc2.list();
    for(Test1 test:reports2){
        test.getTest2().getName();
    }

但我的控制台显示sql是:

   Hibernate: select this_.id as id18_0_, this_.name as name18_0_, this_.test2_id as test3_18_0_ from test1 this_
   Hibernate: select test2x0_.id as id19_1_, test2x0_.name as name19_1_, test1x1_.id as id18_0_, test1x1_.name as name18_0_, test1x1_.test2_id as test3_18_0_ from test2 test2x0_ left outer join test1 test1x1_ on test2x0_.id=test1x1_.test2_id where test2x0_.id=?
   Hibernate: select test1x0_.id as id18_0_, test1x0_.name as name18_0_, test1x0_.test2_id as  test3_18_0_ from test1 test1x0_ where test1x0_.test2_id=?

因为提取是懒惰的,我认为sql是对的,

我将获取类型更改为FetchType.EARGER

Hibernate: select this_.id as id18_1_, this_.name as name18_1_, this_.test2_id as test3_18_1_, test2x2_.id as id19_0_, test2x2_.name as name19_0_ from test1 this_ left outer join test2 test2x2_ on this_.test2_id=test2x2_.id
Hibernate: select test1x0_.id as id18_1_, test1x0_.name as name18_1_, test1x0_.test2_id as test3_18_1_, test2x1_.id as id19_0_, test2x1_.name as name19_0_ from test1 test1x0_ left outer join test2 test2x1_ on test1x0_.test2_id=test2x1_.id where test1x0_.test2_id=?

我不明白第二个sql,它浪费了我的时间

如果我有10000条记录,它会循环10000次。

我怎么能解决它?及时获取所有记录?

1 个答案:

答案 0 :(得分:0)

您可以将setFetchMode用作Join ...例如

 Criteria dc2 = sessionFactory. getCurrentSession().createCriteria(Test1.class,"mr");
 dc2.setFetchMode("test2", FetchMode.JOIN)
    List<Test1> reports2= dc2.list();
    for(Test1 test:reports2){
        test.getTest2().getName();
    }

这样Hibernate应该用一个查询填充test2对象;老实说,我不能说性能,因为在这种情况下,将从DB加载更多数据

我希望它有所帮助

安吉洛