views:

29

answers:

1

Ok I have a 1-to-many mapping between a parent and child class. I can save the parent and it will automatically save the children objects, but problem is when doing a SELECT on the parent class. It seems that I'm getting a Parent object for every Child object in database table. So if I save 1 parent object with 2 child objects, when I use Hibernate select Criteria I get 2 Parent objects!!! All I want is for Hibernate to return 1 parent object with its 2 child objects inside the Set child field.

My mappings must be wrong I guess. Can someone please help with this?

class Parent{
 Long parentId;
 @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
 @JoinColumn(name = "parent_table_id", nullable = false)
 Set childs;
 ....
}

class Child{
 Long childId;

}

Note: the "parent_table_id" references the Parent primary key. Also this value is not mapped into any Parent or Child object. I manually insert this value and only use it in the @JoinColumn annotation. Ok I'm new to this JPA stuff but it seems that Hibernate is automatically inserting the values for field "parent_table_id" in the Child table when I save a Parent with Child objects. Could this be causing the problem?

+1  A: 

Your mapping looks fine, it sounds like what you actually need is:

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

as you're performing an inner join that results in more than one result row being returned in your criteria query.

Affe
Yes that actually fixed my problem. I don't remember having this problem when I was using those Hibernate.hbm.xml mapping files. Also the before and after queries generated are identical!!. I guess by adding DISTINCT_ROOT_ENTITY Hibernate adds a filter to remove duplicate Parent objects.
Marquinio