Hibernate AliasToBean with collection

I have a one-to-many bidirectional relationship defined between parent and child classes. I want to execute a query so that I can return a single parent and a subset of its children in a bean.

public class Parent { private int id; private Set<Child> children = new HashSet<Child>(0); // other fields + getters and setters } public class Child { private Parent parent; private int age; // other fields + getters and setters } 

The result I want to achieve is:

 public class ParentChildWrapper { private Parent parent; private Collection<Child> children; // subset of children } 

I would like to filter the parent id and the childhood column. I tried several combinations of queries to get the desired result.

The following will close but not group the children in the collection in the ParentChildWrapper bean that I defined. The result that I get is a list of objects with 1 instance per child, which matches the age filter:

 Query q = session.createQuery( "SELECT p, c " + "FROM Parent p " + "INNER JOIN p.children c " + "WHERE p.id = :id " + "AND c.age = :age" ); 

I also tried grouping by parent to try to collect all the children into a collection, also to no avail.

Obviously, I could divide this into two separate queries to select a parent, and then select the children I need. But it seems like this should be a fairly common case. Perhaps I do not think about sleep mode.

+4
source share
1 answer

Just do not use a transformer and do not loop:

 List<Object[]> rows = query.list(); Parent parent = null; List<Child> children = new ArrayList<Child>(rows.size()); for (Object[] row : rows) { parent = (Parent) row[0]; children.add((Child) row[1]); } ParentChildWrapper result = new ParentChildWrapper(parent, children); 

This makes 8 lines of trivial code instead of 1, but avoids reflection calls and thus allows safe refactoring.

+4
source

All Articles