title: Inconsistent results when executing JPA's EntityManager.createQuery
body: <p>I am going crazy about an error in my code involving data persistence in Java (JPA). I didn't develop this and I am not at all knowledgeable about this framework, so, sorry in advance about whatever info I fail to present.</p>
  <p>The error in question is that <strong>a query created with EntityManager.createQuery</strong> (a simply select on a table) <strong>returns inconsistent results</strong>. That is to say, if I change a value via the interface, save the changes, and then reload the browser again and again, sometimes I will see the new value and sometimes I will see the old value. There seems to be no pattern by which this happens, for all I know it is random. And while this happens, if I query the MySQL database, I always see the correct value (the 'new' value).</p>
  <p>I don't know what I should even be looking at. The inconsistent values are retrieved from a class annotated as follows:</p>
  <pre><code>@ManagedBean
  @ViewScoped
  public class DivisoreVolumenticoView implements Serializable {
  </code></pre>
  <p>and the kind of object that this EntityManager.createQuery returns is annotated as follows:</p>
  <pre><code>@ManagedBean
  @Entity
  @Table(name = &quot;divisore_volumetrico&quot;)
  public class DivisoreVolumetricoBean implements Serializable {
  </code></pre>
  <p>where the inconsistent property (although this would happen with any of them) is:</p>
  <pre><code>@Column(name = &quot;nazionale&quot;)
  private Double nazionale;
  </code></pre>
  <p>and there are a bunch of other methods annotated as @Transient, and the getters and setters for the properties do not have any annotations.</p>
  <p>The EntityManager on which createQuery is called is retrieved from class below (and when I execute this on my local environment, with every browser refresh sometimes a new object is created and sometimes it isn't):</p>
  <pre><code>public class EMHelper {
      private static final EntityManagerFactory emf;
      private static final ThreadLocal&lt;EntityManager&gt; threadLocal;
  
      static {
          emf = Persistence.createEntityManagerFactory(&quot;persistenceUnit&quot;);
          threadLocal = new ThreadLocal&lt;EntityManager&gt;();
      }
      
      public static EntityManager getEntityManager() {
          EntityManager em = threadLocal.get();
          if (em == null) {
              em = emf.createEntityManager();
              threadLocal.set(em);
          }
          return em;
      }
  </code></pre>
  <p>If you can at least point me in the right direction, I'd be very grateful. For example: since the value in the database is always the correct one, should I assume that there is no problem with the persistence of the change? or could the problem be there and the inconsistencies while retrieving it be just a symptom?</p>
  <p>Thanks in advance.</p>