3

在执行这些步骤时,我得到了 org.hibernate.NonUniqueObjectException。

session.beginTransaction();
TransactionEntry te = (TransactionEntry)session.get(TransactionEntry.class, primaryKey);
session.getTransaction().commit();
.
.
.
session.beginTransaction();
session.saveOrUpdate(te.getAccount());
session.delete(te);
session.delete(te.getTransaction());
session.getTransaction().commit();

我的模型快照如下:

TransactionEntry 类

@Entity
public class TransactionEntry {
    @Id
    @GeneratedValue
    private long txnEntryId;

    @ManyToOne
    @JoinColumn(name = "account")
    private Account account;

    @ManyToOne
    @JoinColumn(name = "txnId")
    private TransactionTable transaction;
}

账户类

@Entity
public class Account {
    @Id
    @GeneratedValue
    private long accountId;
}

事务表类

@Entity
public class TransactionTable {
    @Id
    @GeneratedValue
    private long txnId;

    @OneToMany(targetEntity = TransactionEntry.class, fetch = FetchType.LAZY,
            mappedBy = "transaction", cascade = CascadeType.ALL)
    private List<TransactionEntry> transactionEntries;
}

我收到以下异常:

org.hibernate.NonUniqueObjectException: a different object with the same
identifier value was already associated with the
session: [com.pratikabu.pem.model.Account#1]

如果我删除该 session.delete(te.getTransaction());语句,则代码工作正常,否则将引发上述异常。有什么我想念的吗。

4

2 回答 2

3

这是一步一步发生的事情:

  • session.saveOrUpdate(te.getAccount());Account对象(id为1)附加到会话
  • 在该行session.delete(te.getTransaction());中,在删除之前,hibernate 会尝试加载TransactionEntry对象集合(由于级联,集合中的对象也需要删除)。
  • 但是在TransactionEntry从集合中加载对象时,hibernate 也会加载成员Account对象,因为它是使用具有EAGER默认获取的@ManyToOne注释映射的。
  • 当到达与 id 1TransactionEntry对应的对象时,Account休眠会引发上述异常,因为该异常Account已存在于会话中。
于 2012-09-02T21:27:47.573 回答
1

session.delete(te)- 它会删除TransactionEntry以及TransactionTable因为cascade = CascadeType.ALL 所以session.delete(te.getTransaction()) with this line you wont have any thing这就是它说的原因NonUniqueObjectException

于 2012-09-02T19:50:03.297 回答