使用 orphanRemoval 触发 Hibernate 违反约束 [英] Hibernate triggering constraint violations using orphanRemoval
问题描述
我在使用 JPA/Hibernate (3.5.3) 设置时遇到问题,我在其中有一个实体,即帐户"类,其中包含子实体列表和联系人"实例.我正在尝试能够将 Contact 的实例添加/删除到 List<Contact>帐户的财产.
I'm having trouble with a JPA/Hibernate (3.5.3) setup, where I have an entity, an "Account" class, which has a list of child entities, "Contact" instances. I'm trying to be able to add/remove instances of Contact into a List<Contact> property of Account.
将一个新实例添加到集合中并调用 saveOrUpdate(account) 可以保留所有可爱的东西.如果我然后选择从列表中删除联系人并再次调用 saveOrUpdate,则 SQL Hibernate 似乎产生涉及将 account_id 列设置为 null,这违反了数据库约束.
Adding a new instance into the set and calling saveOrUpdate(account) persists everything lovely. If I then choose to remove the contact from the list and again call saveOrUpdate, the SQL Hibernate seems to produce involves setting the account_id column to null, which violates a database constraint.
我做错了什么?
下面的代码显然是一个简化的摘要,但我认为它涵盖了问题,因为我在不同的代码中看到相同的结果,这真的很简单.
The code below is clearly a simplified abstract but I think it covers the problem as I'm seeing the same results in different code, which really is about this simple.
SQL:
CREATE TABLE account ( INT account_id );
CREATE TABLE contact ( INT contact_id, INT account_id REFERENCES account (account_id) );
Java:
@Entity
class Account {
@Id
@Column
public Long id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "account_id")
public List<Contact> contacts;
}
@Entity
class Contact {
@Id
@Column
public Long id;
@ManyToOne(optional = false)
@JoinColumn(name = "account_id", nullable = false)
public Account account;
}
Account account = new Account();
Contact contact = new Contact();
account.contacts.add(contact);
saveOrUpdate(account);
// some time later, like another servlet request....
account.contacts.remove(contact);
saveOrUpdate(account);
结果:
UPDATE contact SET account_id = null WHERE contact_id = ?
编辑 #1:
这可能是一个错误http://opensource.atlassian.com/projects/hibernate/browse/HHH-5091
编辑#2:
我有一个似乎有效的解决方案,但涉及使用 Hibernate API
I've got a solution that seems to work, but involves using the Hibernate API
class Account {
@SuppressWarnings("deprecation")
@OneToMany(cascade = CascadeType.ALL, mappedBy = "account")
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
@JoinColumn(name = "account_id", nullable = false)
private Set<Contact> contacts = new HashSet<Contact>();
}
class Contact {
@ManyToOne(optional = false)
@JoinColumn(name = "account_id", nullable = false)
private Account account;
}
由于 Hibernate CascadeType.DELETE_ORPHAN 已被弃用,我不得不假设它已被 JPA2 版本取代,但实现中缺少一些东西.
Since Hibernate CascadeType.DELETE_ORPHAN is deprecated, I'm having to assume that it has been superseded by the JPA2 version, but the implementation is lacking something.
推荐答案
备注:
- 因为你有一个双向关联,你需要添加一个
mappedBy
属性来声明关联的拥有方. - 另外不要忘记在使用双向关联时需要管理链接的两端,我建议为此使用防御方法(如下所示).
- 并且您必须在
Contact
上实现equals
和hashCode
.
- Since you have a bi-directional association, you need to add a
mappedBy
attribute to declare the owning side of the association. - Also don't forget that you need to manage both sides of the link when working with bi-directional associations and I suggest to use defensive methods for this (shown below).
- And you must implement
equals
andhashCode
onContact
.
所以,在Account
中,修改映射如下:
So, in Account
, modify the mapping like this:
@Entity
public class Account {
@Id @GeneratedValue
public Long id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "account", orphanRemoval = true)
public List<Contact> contacts = new ArrayList<Contact>();
public void addToContacts(Contact contact) {
this.contacts.add(contact);
contact.setAccount(this);
}
public void removeFromContacts(Contact contact) {
this.contacts.remove(contact);
contact.setAccount(null);
}
// getters, setters
}
在Contact
中,重要的部分是@ManyToOne
字段应该将optional
标志设置为false
:
In Contact
, the important part is that the @ManyToOne
field should have the optional
flag set to false
:
@Entity
public class Contact {
@Id @GeneratedValue
public Long id;
@ManyToOne(optional = false)
public Account account;
// getters, setters, equals, hashCode
}
经过这些修改后,以下内容才有效:
With these modifications, the following just works:
Account account = new Account();
Contact contact = new Contact();
account.addToContact(contact);
em.persist(account);
em.flush();
assertNotNull(account.getId());
assertNotNull(account.getContacts().get(0).getId());
assertEquals(1, account.getContacts().size());
account.removeFromContact(contact);
em.merge(account);
em.flush();
assertEquals(0, account.getContacts().size());
和预期的一样,孤立的 Contact
被删除了.使用 Hibernate 3.5.3-Final 测试.
And the orphaned Contact
gets deleted, as expected. Tested with Hibernate 3.5.3-Final.
这篇关于使用 orphanRemoval 触发 Hibernate 违反约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!