I'm getting org.hibernate.NonUniqueObjectException while performing these steps.
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();
Snapshot of my model is as follows:
TransactionEntry class
@Entity
public class TransactionEntry {
@Id
@GeneratedValue
private long txnEntryId;
@ManyToOne
@JoinColumn(name = "account")
private Account account;
@ManyToOne
@JoinColumn(name = "txnId")
private TransactionTable transaction;
}
Account Class
@Entity
public class Account {
@Id
@GeneratedValue
private long accountId;
}
TransactionTable class
@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;
}
I'm getting the following exception:
org.hibernate.NonUniqueObjectException: a different object with the same
identifier value was already associated with the
session: [com.pratikabu.pem.model.Account#1]
If I remove the session.delete(te.getTransaction());
statement then the code is working fine or else it is throwing the above exception. Is there something I'm missing.
Here is what's happening step by step:
session.saveOrUpdate(te.getAccount());
attach the Account
object ( with id 1 ) to the session session.delete(te.getTransaction());
, before deleting, hibernate tries to load the collection of TransactionEntry
objects (because of the cascade, the objects in the collection need to be deleted too). TransactionEntry
objects from the collection, hibernate will load the member Account
object too because it's mapped with a @ManyToOne annotation that has an EAGER default fetch. TransactionEntry
object that corresponds to the Account
with id 1 hibernate throws the above exception because that Account
already exists in the session. session.delete(te)
- 它将删除TransactionEntry
以及TransactionTable
因为cascade = CascadeType.ALL
所以session.delete(te.getTransaction()) with this line you wont have any thing
这就是为什么它说NonUniqueObjectException
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.