gpt4 book ai didi

database - Hierarchical Hibernate,执行了多少查询?

转载 作者:搜寻专家 更新时间:2023-10-30 20:45:51 26 4
gpt4 key购买 nike

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

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

我想说这是废话,因为可连接的实体应该在一个查询中被关闭,对吧?我在这里遗漏了什么吗?

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

最佳答案

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

关于database - Hierarchical Hibernate,执行了多少查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2859766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com