Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate NonUniqueObjectException: a different object with the same identifier value was already associated with the session:

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.

like image 901
TechFind Avatar asked Sep 22 '14 23:09

TechFind


1 Answers

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;
    }
like image 195
kent Avatar answered Oct 25 '22 13:10

kent