Hierarchical Hierarchnate,执行了多少个查询?

时间:2010-05-18 18:03:28

标签: database hibernate optimization orm

所以我一直在处理一个家庭酿造DB框架,它有一些严重的缺陷,使用的理由是不使用ORM将节省执行的查询数量。

如果我从可连接对象层次结构的顶层选择所有可能的记录,那么在使用ORM(例如Hibernate)时将对数据库进行多少次单独调用?

我觉得要对此进行废话,因为可连接的实体应该在一个查询中被删除,对吧?我在这里错过了什么吗?

注意:在这种情况下,延迟初始化并不重要,因为将使用所有记录。

2 个答案:

答案 0 :(得分:1)

Hibernate几乎总是使用单个查询检索对象层次结构;我不记得看到它不这样做了。无论如何,它很容易测试。通过这个非常简单的映射:

@Entity
public static class Person {
    @Id
    public String name;
}

@Entity
public static class Student extends Person {
    public float averageGrade;
}

@Entity
public static class Teacher extends Person {
    public float salary;
}

然后Hibernate为一个非常简单的浏览查询(sessionFactory.openSession().createCriteria(Person.class).list();)提供了以下结果。

父级@Inheritance(strategy = InheritanceType.SINGLE_TABLE)

select this_.name as name0_0_, this_.averageGrade as averageG3_0_0_, 
  this_.salary as salary0_0_, this_.DTYPE as DTYPE0_0_ from HibernateTest$Person this_

父级@Inheritance(strategy = InheritanceType.JOINED)

select this_.name as name0_0_, this_1_.averageGrade as averageG1_1_0_, 
  this_2_.salary as salary2_0_, case when this_1_.name is not null then 1 
  when this_2_.name is not null then 2 when this_.name is not null then 0 
  end as clazz_0_ from HibernateTest$Person this_ left outer 
  join HibernateTest$Student this_1_ on this_.name=this_1_.name left outer join
  HibernateTest$Teacher this_2_ on this_.name=this_2_.name

父级@Inheritance(strategy = InheritanceType.JOINED)

select this_.name as name0_0_, this_.averageGrade as averageG1_1_0_, 
  this_.salary as salary2_0_, this_.clazz_ as clazz_0_ from 
  ( select null as averageGrade, name, null as salary, 0 as clazz_ 
  from HibernateTest$Person union select averageGrade, name, null as salary, 
  1 as clazz_ from HibernateTest$Student union select null as averageGrade, 
  name, salary, 2 as clazz_ from HibernateTest$Teacher ) this_

如您所见,每个查询都是一个查询,根据映射类型,JOINUNION是合适的。

答案 1 :(得分:0)

Bobah是对的,

你应该试试hibernate以查看将多少请求发送到数据库,但是,在hibernate中你也可以使用HQL指定和调整特定请求。

除了使用hibernate工具,您还可以使用P6spy driver,这样您就可以看到hibernate发送到数据库的所有请求,以及请求的每个过滤器的值。

相关问题