Hibernate - 如何仅保留父级,保持子级不变

use*_*237 8 java hibernate

有人可以帮我理解如何配置hibernate来做我想做的事.

我有一个父母实体"公寓",其中"房间"列表为儿童.我有一个表格来编辑"公寓",在该表格中,我列出了所有儿童"房间"仅供参考.客房以单独的形式添加和编辑.

因为我在appartment-form中列出了房间,我将lazyloading设置为false:

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

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

那么如何配置hibernate只能保留我的Appartment-object.而不是触摸孩子们?

这是我的保存动作:

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;
}
Run Code Online (Sandbox Code Playgroud)

小智 8

这很简单.无需重新填充您的孩子,或创建单独的DTO.

如果你永远不会坚持孩子,只需在你的joincolumn注释中添加insertable = false,updatable = false.像这样:

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

  • @user829237:您意识到这意味着您*永远*不能通过将房间添加到房间列表中来将房间添加到公寓中,对吗? (2认同)