0

I got a puzzling EntityExistsException in the following query -

TypedQuery<T> typedQuery = em.createQuery(query);
return result = typedQuery.getSingleResult(); // <-- exception thrown here

I thought this exception should normally occur when persisting, not when retrieving. Can you please shed some clues under which circumstances EntityExistsException can occur during a retrieval operation? Thanks.

javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [...@d8e152db] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1735) ~[hibernate-entitymanager-4.3.0.Final.jar:4.3.0.Final] at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677) ~[hibernate-entitymanager-4.3.0.Final.jar:4.3.0.Final] at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:524) ~[hibernate-entitymanager-4.3.0.Final.jar:4.3.0.Final] at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:71) ~[hibernate-entitymanager-4.3.0.Final.jar:4.3.0.Final] ... ...

hummingV
  • 1,014
  • 1
  • 11
  • 25
  • may be this http://stackoverflow.com/questions/13762713/a-different-object-with-the-same-identifier-value-was-already-associated-with-th – Pramod S. Nikam Aug 04 '14 at 12:29

1 Answers1

1

Your em might have an object already loaded in it, when you do typedQuery.getSingleResult() you are reloading the existing object that is in hibernate cache(causes the above exception). So before running the typed query flush and clear see if it works

em.flush();
em.clear();

//and your typed query goes here

Or if you know the exact object that is causing then you can do

session.evict(theExactObject)

Elbek
  • 3,434
  • 6
  • 37
  • 49
  • Why doesn't hibernate then return the existing object in the cache? Or is there a way to do so? I am implementating a web-app, and by nature when user submits a form, I have lost reference to the entity (only have string value of ID). So, I am trying to re-query the entity object. – hummingV Aug 05 '14 at 02:33
  • You shouldn't requery, instead use `refresh()` method, so entity manage should bring the latest object changes from db for the object. – Elbek Aug 05 '14 at 17:32