gpt4 book ai didi

java - [Hibernate] 将临时对象与子对象合并

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:39:37 25 4
gpt4 key购买 nike

我在合并方面遇到了一些问题。我的更新方法是这样工作的:

void update(Parent parent) {
evict(parent);
merge(parent);
}

我的类(class):

Parent {

Long id;

List<Children> childrens;

@OneToMany(targetEntity =ChildrenImpl.class, fetch=FetchType.LAZY)
@JoinColumn(name="PARENT")
@org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.ALL)
List<Children> getChildrens(){...}

@Id
Long getId() {...}

}



Children{

Parent parent;

@ManyToOne(targetEntity = ParentImpl.class, fetch = FetchType.LAZY)
@org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.ALL)
@JoinColumn(name = "PARENT", nullable = false)
Parent getParent(){...}

}

当我创建一个新的父( transient )对象并添加新的子对象并尝试更新(逐出和合并)时,日志会在刷新 hibernate session 后向我显示:

INSERT PARENT //everythings here is ok.

INSERT CHILDREN // but without parent id(id=null)

顺序很好,但 child 在插入时没有父 ID。当 Parent 保存在数据库中时,一切正常,然后 children 总是有一个好的 id。

关于我应该如何从 transient 对象(从持久对象中获取 id)的任何想法。

问候KZ.

最佳答案

您无法从 transient 对象获取 ID,根据定义, transient 对象没有 ID。

如果创建了一个新对象,为什么要进行合并?当您创建一个新对象时,您应该保存它。如果更改现有对象的值,则应更新它。只有当一个持久的对象变得分离并且您需要重新附加它时,您才应该合并。

关于java - [Hibernate] 将临时对象与子对象合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4281230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com