What is best practice about having one-many hibernate

Posted by Patrick on Stack Overflow See other posts from Stack Overflow or by Patrick
Published on 2010-05-20T04:23:38Z Indexed on 2010/05/20 4:30 UTC
Read the original article Hit count: 258

Filed under:
|
|

Hi all, I believe this is a common scenario. Say I have a one-many mapping in hibernate Category has many Item Category:

@OneToMany(
    cascade = {CascadeType.ALL},fetch = FetchType.LAZY)
@JoinColumn(name="category_id")
@Cascade(
    value = org.hibernate.annotations.CascadeType.DELETE_ORPHAN
)
private List<Item> items;

Item:

@ManyToOne(targetEntity=Category.class,fetch=FetchType.EAGER)
@JoinColumn(name="category_id",insertable=false,updatable=false)
private Category category;

All works fine. I use Category to fully control Item's life cycle. But, when I am writing code to update Category, first I get Category out from DB. Then pass it to UI. User fill in altered values for Category and pass back. Here comes the problem. Because I only pass around Category information not Item. Therefore the Item collection will be empty. When I call saveOrUpdate, it will clean out all associations.

Any suggestion on what's best to address this? I think the advantage of having Category controls Item is to easily main the order of Item and not to confuse bi-directly. But what about situation that you do want to just update Category it self? Load it first and merge?

Thank you.

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about one-to-many