I have tree of classes:
classA {
classB b;
classC c;
.....
}
I have HQL query like this:
If you use Hibernate 5.x, you can use a ResultTransformer
, as, e.g., described in this blog post. Note that ResultTransformer
will be @Deprecated in Hibernate 6.
Applied to your scenario:
List classDDTOs = entityManager
.createQuery(
"SELECT a.field1, b.field2, c.field3, c.field4 " +
"FROM a LEFT OUTER JOIN b ON a.id = b.fk " +
"LEFT OUTER JOIN c ON b.id = c.fk")
.unwrap( org.hibernate.query.Query.class )
.setResultTransformer(
new ResultTransformer() {
@Override
public Object transformTuple(
Object[] tuple,
String[] aliases) {
return new classD(
(Type1) tuple[0],
(Type2) tuple[1],
(Type3) tuple[1],
);
}
@Override
public List transformList(List collection) {
return collection;
}
}
)
.getResultList();
The above code assumes classD
has a constructor classD(Type1, Type2, Type3)
.
An advantage of this approach is that it lets you define the ResultTransformer
once and allows you to reuse it in all queries with the same result type.