Hierarchical hibernation, how many queries are running?
So, I was dealing with brew's home database framework which has some serious flaws, the excuse to use is that not using an ORM will save on the number of queries executed.
If I select all possible records from the top level of the hierarchy of the objects being joined, how many separate calls to the DB would be made when using an ORM (like Hibernate)?
It seems to me that calling this is nonsense, since the objects being merged have to be brought down by a single request, right? Did I miss something?
Note: lazy initialization is irrelevant in this scenario as all records will be used.
a source to share
Hibernate will almost always retrieve object hierarchies using a single query; I don't remember doing it any other way. Anyway, it's easy to check. With this very simple mapping:
@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 then gives me the following results for a very simple view ( sessionFactory.openSession().createCriteria(Person.class).list();
) query .
C @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
from parent:
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_
C @Inheritance(strategy = InheritanceType.JOINED)
from parent:
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
C @Inheritance(strategy = InheritanceType.JOINED)
from parent:
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_
As you can see, each one represents one request with JOIN
or UNION
depending on the display type.
a source to share
Boba is right
You should give hibernate a try to see how many queries will be sent to the database, however in hibernate you can also specify and customize a specific query using HQL.
In addition to the hibernate tools, you can also use the P6spy driver so that you can see the entire hibernation request to your database with a value for each request filter.
a source to share