Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Check to see if an entity is managed by the persistence context

 
Deniz Atak
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi I have a code where I try to check if an entity is managed by the persistence context. If it does it will perform an action, if it doesn't it will perform another action. My code is:



I might have a logical mistake in trying first find and then contains method.. but I don't know.

Thanks in advance for your help.
 
lokesh sree
Ranch Hand
Posts: 100
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In case of transaction scoped persistence context:
An entity will be loaded into the persistence context, if it is fetched in the scope of a transaction.
And it will get detached , the context gets closed, when the transaction ends.

So, I believe that, if the code block that you have posted is running in the scope of a tx, the contains() call that is made should always return true for any entity.
 
Deniz Atak
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for the late answer. Thanks for your reply.

Your explanation is right if the entity exists. But I am trying to handle the case when it doesn't exist. It works fine in the true case (=when .contains returns true) but doesn't catch the null pointer exception.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic