Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...