My Code:
I am trying to do either update/insert. It gets inserted properly, only problem is when I try to update it gives below error message.
private String sessionType=null;
public String getAccountsDetails(List<Account> accountList) {
Session session = sessionFactory.openSession();
for (Account account : accountList) {
AccountDetails accountDetails = new AccountDetails();
accountDetails.setAccountsId(Long.parseLong(account.getId()));
accountDetails.setAccounttype(account.getAccountType().value());
Query query = session.createQuery("from QBAccounts qba where qba.accountsId=:accId");
List<AccountDetails> queryList = query.setParameter("accId", accountDetails.getAccountsId()).list();
if(queryList.size()>0){
session.update(accountDetails);
}else{
session.save(accountDetails);
}
}
session.flush();
session.beginTransaction().commit();
session.clear();
session.close();
return "Successfully data updated into table";
}
Error:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.trinet.mulesoft.quickbooks.dto.AccountDetails#0]
at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:638)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:305)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:246)
EDIT 2:
I have used
session.merge(accountDetails)
there is no error, but it always does insert data into db instead of update.
I had this error when opening two sessions. One session for a User and another session for an object that has its primary key a foreign key from User. With this,the two session has the same primary key or identifier. I solved this by session.clear before session.update(type).
public T update(T type) {
Session session = getSession();
session.clear();
session.update( type );
session.flush();
return type;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With