title: Is it normal for JPA to return detached instances for @MapsId field?
body: <h2>Summary</h2>
  
  <p>I'am very suprised by the behaviour I'm seeing with the following code:</p>
  
  <pre><code>@Repository
  @Transactional
  public class SuiviDao {
  
  
      public Suivi getSuivi(SuiviPK pk) {
          final Suivi suivi = em.find(Suivi.class, pk);
          assert em.contains(suivi);
          // throws occasionally an assertion error
          assert em.contains(suivi.getCommune());
          return suivi;
      }
  }
  </code></pre>
  
  <p>I would expect having managed entities returned by the <code>find</code> method call.
  This is always the case for the returned <code>suivi</code>.
  However, it happens that the <code>commune</code> instance is not managed.
  Is it normal JPA behaviour? Or is it something specific to Hibernate (I'm using version 4.3.7) ?</p>
  
  <hr>
  
  <h2>Details</h2>
  
  <p>There is a simple workaround (see below):</p>
  
  <pre><code>  if (!em.contains(suivi.getCommune())) {
        final Commune commune = em.find(Commune.class, suivi.getCommune().getId());
        suivi.setCommune(commune);
    }
  </code></pre>
  
  <hr>
  
  <p>By digging further, I found that in the case were a non-managed Commune entity is returned, the entity is not loaded from the DB, but from Hibernate's session cache.</p>
  
  <hr>
  
  <p>Relevant part of the related classes:</p>
  
  <pre><code>@Entity
  public class Suivi {
      @EmbeddedId
      private SuiviPK pk = new SuiviPK();
  
      @MapsId("commune")
      @ManyToOne
      private Commune commune;
  
      @MapsId("echeance")
      @NotNull
      @ManyToOne(cascade = { CascadeType.REFRESH })
      private Echeance echeance;
  
      // remaining of class body
  }
  
  @Embeddable
  public class SuiviPK implements Serializable {
  
      @Column(name = "ECHEANCE")
      private Long echeance;
  
      @Column(name = "COMMUNE")
      private Long commune;
  
      // remaining of class body
  }
  </code></pre>