简体   繁体   English

Hibernate - 如何只保留父母,让孩子保持原样

[英]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.有人可以帮我了解如何配置 hibernate 来做我想做的事。

I have a parent entity "Appartment" with a List of "Room"s as children.我有一个父实体“Appartment”,其中有一个“房间”列表作为子实体。 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:因此,因为我在公寓表单中列出了房间,所以我将延迟加载设置为 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).在数据库中,它们不会被删除,而是被取消引用(如 appartmentId = null)。

So how can I configure hibernate to only persist my Appartment-object.那么如何配置 hibernate 以仅保留我的 Appartment 对象。 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.无需重新填充您的孩子,或创建单独的 DTO。

If you are never going to persist the children just add insertable=false, updatable=false to your joincolumn annotation.如果您永远不会保留孩子,只需将 insertable=false, updatable=false 添加到您的 joincolumn 注释中。 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.如果您告诉 Hibernate 保存/更新其中没有房间的公寓,Hibernate 只会从公寓中删除房间。

Instead of using persistent entities, consider using DTOs (you can call them a page model in the case of web pages).考虑使用 DTO,而不是使用持久实体(在 web 页面的情况下,您可以将它们称为页面 model)。 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.但是你应该为此付出代价——你正在向你的系统添加新的类,你必须想出一种将实体转换为 DTO 并向后转换的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM