EntityManager.contains() returns false after persist()

niccolo m. picture niccolo m. · Dec 16, 2011 · Viewed 8.7k times · Source

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

Answer

James Bassett picture James Bassett · Dec 16, 2011

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?