开发者

What is best practice about having one-many hibernate

I believe this is a common scenario. Say I have a one-many mapping in hibernate: Category has many Items


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 the Items, the Items collection will therefore 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 controlling Items is to easily main the order of Items and not to confuse bi-directly.

But what about situation that you do want to just update Category itself? Load it first and merge?


For your issue, if we see from high level without going into code, I am seeing that problem is not with hibernate configuration but it is with how you are handling entities. I suggest you to modify the way you are handling your entities in below ways,

1) You have not mentioned how you are fetching Category object before passing it to UI. So if you simple fetch category object using get load method, then you can simply create separate initializer method which can load items collection by simply calling getter method. By getter method lazy loaded collection of items will get populated & then you can pass it to UI. User will just modify category so items will remain as it is. THen afterwards you can save that entity, so items will stay as it is.

2) If you don't want to load items collection before passing on to UI, then you can just fetch category object without items collection loaded. Pass it to UI. Once user modifies & passes it back, then instead of saving it directly, I suggest you to first fetch latest category object for that category_id & get its items loaded by calling getters, then populate altered values from UI returned category into this latest fetched category. Now you can save this merged object so you items collection is safe.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜