本文介绍了休眠 - 如何只保留父母,让孩子保持原样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个父级实体Appartment,其中包含一个房间列表作为孩子。
我有一个表格来编辑公寓,在这个表格中,我列出了所有孩子的房间,仅供参考。房间被添加和编辑在一个单独的窗体中。



所以,因为我列出房间的公寓形式,我设置了lazyloading为false:

  @OneToMany 
@JoinColumn(name =appartmentId)
@LazyCollection(LazyCollectionOption.FALSE)
private List< ;客房>房间;

但是,如果我编辑公寓并将其存储,所有公寓房间会突然消失。在数据库中,它们不会被删除,而是被解除引用(如appartmentId = null)。

那么如何配置hibernate来只保留我的Appartment对象。而不是触摸孩子?



这是我的保存动作:

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

appartment = appartmentManager.save(appartment);

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

返回SUCCESS;


解决方案

这非常简单。无需重新填充您的孩子,或创建单独的DTO。



如果您永远不会坚持孩子,只需将joinable = false,updatable = false添加到联合列注释中即可。像这样:

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


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;

这篇关于休眠 - 如何只保留父母,让孩子保持原样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:33