Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityManager.contains() returns false after persist()

The documentation for EntityManager.persist() says it will Make an instance managed and persistent.

It is persisting the entity to the database, but when I call the EntityManager.contains() method to check if the entity that I just persisted is managed it returns false.

I just want to know why does this happen? Maybe are there somethings that I was not able to do or something I overlooked?

Suggestions would be appreciated :D

like image 997
chip Avatar asked Dec 16 '11 03:12

chip


1 Answers

That's really strange. According the the Sun EJB3 spec:

The contains() method can be used to determine whether an entity instance is managed in the current persistence context.

The contains method returns true:

  • If the entity has been retrieved from the database, and has not been removed or detached.
  • If the entity instance is new, and the persist method has been called on the entity or the persist operation has been cascaded to it.

The contains method returns false:

  • If the instance is detached.
  • If the remove method has been called on the entity, or the remove operation has been cascaded to it.
  • If the instance is new, and the persist method has not been called on the entity or the persist operation has not been cascaded to it.

Note that the effect of the cascading of persist or remove is immediately visible to the contains method, whereas the actual insertion or deletion of the database representation for the entity may be deferred until the end of the transaction.

Are you calling contains in the same transaction?

like image 80
James Bassett Avatar answered Sep 30 '22 19:09

James Bassett