Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Query Language (HQL) - Queries for lazy/no-lazy loading

Tags:

hibernate

hql

I have a structure like this:

  • A contains collection of B (mapped as not-lazy)
  • B contains collection of C (mapped as not-lazy)

I'd like to make a query, that retrieves A objects, that contain B objects without the C objects within them. Is that possible? The other way around will work for me too (if B-C relation is mapped lazy and the query retrieves A, containing B and C).

Thanks!

like image 953
Mooncrosser Avatar asked May 14 '12 13:05

Mooncrosser


People also ask

Which method uses lazy loading in the hibernate session?

In Hibernate, there are two main components which can be lazy loaded. They are namely Entities and Collections. An Entity represents a relational data in database, whereas a collection represents collection of children for an entity.

Is HQL faster than SQL?

You can select only certain columns with HQL, too, for example you can use select column from table in HQL. Native SQL is not necessarily faster than HQL. HQL finally also is translated into SQL (you can see the generated statement when running the application with the show_sql property set to true).

How does Hibernate HQL work?

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.


1 Answers

No, it's not possible. Since you marked the association itself as eagerly-loaded, Hibernate will always load this association eagerly.

If you mark the association as lazy (the default for toMany associations), then you have th option of eagerly fetching them in a query, using a join fetch:

select a from A a left join fetch a.bs b left join fetch b.cs

Note that this will not work if both of the collections are bags (i.e. Lists without index column).

like image 183
JB Nizet Avatar answered Jun 10 '23 09:06

JB Nizet