gpt4 book ai didi

java - 如何更新包含 "orphanRemoval=true"的 JPA 字段?

转载 作者:行者123 更新时间:2023-12-01 22:55:13 27 4
gpt4 key购买 nike

我正在使用 JPA 2.0 和 Hibernate 4.1.0.Final。我有这个实体(用户和地址对象之间的单向关系)...

@Entity
@Table(name = "user")
public class User implements Serializable
{

@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}, orphanRemoval=true)
@JoinTable(name = "user_address", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "address_id"))
private Set<Address> addresses;

在我的“updateUser”方法中,我有这段代码

        user.setAddresses(addresses);

调用

public void setAddresses(Set<Address> addresses)
{
if (this.addresses == null)
{
this.addresses = new HashSet<Address>();
}
this.addresses.clear();
if (addresses != null)
{
this.addresses.addAll(addresses);
} // if
}

问题是仅当“地址”是新对象时才会保存地址,而不是重新保存现有的地址实体。我需要做什么才能用现有地址更新我的用户?

编辑:这是我保存实体的方法...

protected Object save(Object obj)
{
if (obj != null)
{
final Object id = getId(obj);
if (id == null)
{
m_entityManager.persist(obj);
}
else
{
obj = m_entityManager.merge(obj);
} // if
} // if
return obj;
} // save

最佳答案

为了保存用户和地址,您需要调用 session.merge:

user.setAddresses(addresses);
session.merge(user);

合并将从用户级联到地址,并且它将适用于新实体和分离实体。

此外,清除列表并重新添加元素的效果也不是很好。我建议这样做:

//always initialize the children ollections
private Set<Address> addresses = new HashSet<Address>();

//make sure equals/hashcode are implemented according to the business key semantics
//don't use the entity id for equals and hashcod

public void setAddresses(Set<Address> addresses) {
//1. remove the existing addresses that are not found in the new ones
this.addresses.retainAll(addresses);
//2. add the new addresses too, the common ones will be ignored by the Set semantics
this.addresses.addAll(addresses);
}

关于java - 如何更新包含 "orphanRemoval=true"的 JPA 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24186767/

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