从 JPA 实体的列表中删除项目

Delete an item from a list in a JPA entity

我想从实体的列表中删除一个项目。我有这个实体:

@Entity
public class PairingCommit extends Model
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "commit")
    public List<CommitItem> items;
}

我执行以下操作来删除项目:

commit.items.remove(item);
commit.update();

但它不会从数据库中删除对象。 我想我错过了什么...

编辑:经过一些搜索,我不确定是否使用 JPA...我正在使用使用 Ebean 的 Play 框架 2...但似乎我可以访问 JPA 注释..

我的第一个问题是尝试像这样直接删除项目:

CommitItem.byId(id).delete();

但是它给出了一个 OptimisticLockException。

您应该对项目调用 EntityManager 的删除方法。

EntityManager em;

item = em.merge(item); // Now item is attached
em.find(PairingCommit.class, [Pairing Commit PK]).items.remove(item);
em.remove(item);

看看这个 question/answer. CascadeType 注释会将 EntityManager 操作传播到链接的实体。您的代码当前设置的方式,调用

entityManager.remove(pairingCommit);

也会删除 PairingCommit 链接到的所有 CommitItems,但是

commit.items.remove(item);

不是 EntityManager 操作,因此不会传播任何内容。

您可以直接使用 EntityManager 删除链接的项目。

specification 说:

It is particularly important to ensure that changes to the inverse side of a relationship result in appropriate updates on the owning side, so as to ensure the changes are not lost when they are synchronized to the database.

因此,您必须从关系的拥有方删除:

commitItem.setCommit(null);

好的,我已经解决了Optimistick Lock的问题。就是mysql没有比较浮点数。我已经传递到 DECIMAL 类型并且现在工作正常。 但是我不明白为什么删除列表不起作用。

这里有一篇关于 Optimistick 锁如何工作的文章:http://www.avaje.org/occ.html