开发者

JPA one-to-many query result problem

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开发者_Python百科 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜