开发者

Hibernate - How to persist only the parent, keeping the children as they are

开发者 https://www.devze.com 2023-03-28 12:35 出处:网络
Can someone please help me understand how to configure hibernate to do what i want. I have a parent开发者_开发技巧 entity \"Appartment\" with a List of \"Room\"s as children.

Can someone please help me understand how to configure hibernate to do what i want.

I have a parent开发者_开发技巧 entity "Appartment" with a List of "Room"s as children. I have a form to edit "Appartment"s and within that form i have listed all of the children "Room"s just for informative purposes. Rooms are added and edited in a separate form.

So because i am listing the rooms in the appartment-form i have set lazyloading to false:

    @OneToMany
@JoinColumn (name = "appartmentId")
@LazyCollection (LazyCollectionOption.FALSE)
private List<Room> room;

But if I edit an appartment and store it, all the appartments rooms suddenly dissappear. In the database they are not deleted, but dereferenced (as in appartmentId = null).

So how can I configure hibernate to only persist my Appartment-object. And not touch the children at all?

This is my save-action:

public String save() throws Exception {
    boolean isNew = (appartment.getAppartmentId() == null);

    appartment = appartmentManager.save(appartment);

    String key = (isNew) ? "appartment.added" : "appartment.updated";
    saveMessage(getText(key));

    return SUCCESS;
}


This is really simple. No need to repopulate your children, or create separate DTO's.

If you are never going to persist the children just add insertable=false, updatable=false to your joincolumn annotation. Like this:

@OneToMany
@JoinColumn (name = "appartmentId", insertable = false, updatable = false)
@Fetch(value = FetchMode.JOIN)
private List<Room> room;


  1. Don't disable lazy fetching in a mapping. Use fetching strategies for performance tuning.
  2. Hibernate will only remove the Rooms from an Apartment if you tell it to save/update an Apartment that has no Rooms in it.


Instead of using persistent entities, consider using DTOs (you can call them a page model in the case of web pages). They can give you a flexibility to depict information you want and show it in the format you want. But you should pay for this - you're adding new classes to your system and you have to come up with a way to transform entities to DTOs and backward.

0

精彩评论

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