EntityManager.contains() returns false after persist()
Asked Answered
F

2

7

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

Frosty answered 16/12, 2011 at 3:47 Comment(1)
Can you post your code in which you persist and reads the EntityManager's content?Brookite
S
5

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?

Statism answered 16/12, 2011 at 3:58 Comment(2)
I do believe I am in the same transaction but I am not really sure because I am not defining where the transaction should begin and commit because I left that to the container. But I think why I am not getting the persisted entity is because of the primary key. One of the primary keys should be coming from the database and I can't retrieve that. Anyway, I will just try a different approach to get this done. Thanks for the info though :DFrosty
Couple things come to mind: either the transaaction is not committed and thus the entity is not "officially contained", or if you have a different instance of the object? The contains method specifically checks if the provided entity is being managed within the current persistence context, not just if there's another instance of the same entity in memory.Dialectician
F
0

we did some workaround, rather than persisting > refreshing, we just took the autogenerated key from the datastore and assign it manually to the entity's key fields and then persist it.

Frosty answered 17/12, 2011 at 9:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.