1 Reply Latest reply on Jun 17, 2011 3:19 AM by Leo van den berg

    Persistence Context issues

    Vu Pham Newbie

      Hi all,

      I have an issue which I can't understand it. In my code, I have something like:

       Employee e = getInstance();
       if (entityManager.contains(e)) {

      In the first line of code, I can get the Employee object (I already set Id for Employee so I can get the right object). In the second line of code, I check if it exists in the persistence context or not. But it returns FALSE. How can it happen like that?

      If I get the Employee object again like:

      Employee e = entityManager.find(Employee.class, getInstance().getId());  
      if (entityManager.contains(e)) {

      This time, the checking will returns TRUE.

      Can you explain me what happen? Thanks very much.

        • 1. Re: Persistence Context issues
          Leo van den berg Master


          I never use contains. The API states:

          Check if the instance belongs to the current persistence context

          and I can imagine that after saving and loosing the actual EntityManager,  a call to contains with a new entityManager will return false. I assume you want to know if the entity is in the database (that's something different), so the second method does that for you (it retrieves it if it exists and then puts it in the context (!) another method is refresh, which does exactly what it staes: It takes the data from the DB and refreshes the entity..

          If you keep everything in the same conversation it will probably return true with contains, because it won't dis-connect the entityManager.