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 theAccountobject (with id 1) to the sessionsession.delete(te.getTransaction());, before deleting, hibernate tries to load the collection ofTransactionEntryobjects (because of the cascade, the objects in the collection need to be deleted too).TransactionEntryobjects from the collection, hibernate will load the memberAccountobject too because it’s mapped with a @ManyToOne annotation that has an EAGER default fetch.TransactionEntryobject that corresponds to theAccountwith id 1 hibernate throws the above exception because thatAccountalready exists in the session.