title: Jackson JPA persisting foreign key composite-id fails
body: <p>I have a JPA entity with a foreign key being part of a composite-id:</p>
  
  <pre><code>@Entity
  @IdClass(CustomerId.class)
  public class Customer {
  
      @Id
      public String id;
  
      @Id
      @ManyToOne
      public Company company;
  
  }
  
  public class CustomerId  {
  
      public String id;
  
      public String company;
  
  }
  
  @Entity
  public class Company {
  
      @Id
      public String id;
  
      public String name;
  
  }
  </code></pre>
  
  <p>and it works. Problem is when I receive a JSON object to be persisted and Jackson unserializes it to a POJO:</p>
  
  <pre><code>{
      "id": "Cust0001",
      "company": {
          "id": "Comp1"
       }
  }
  </code></pre>
  
  <p>and this the JAX-RS resource:</p>
  
  <pre><code>@Path("/customers")
  public class CustomerResource {
  
      @PersistenceContext
      EntityManager em;
  
      @POST
      @Consumes(MediaType.APPLICATION_JSON)
      public void post(Customer customer) {
          em.persist(customer);
      }
  
  }
  </code></pre>
  
  <p>this fails, since JPA (I use Hibernate) tries to cascade <code>persist</code> to an unmanaged instance of <code>Company</code> with <code>id</code> "Comp1", thus throwing a <code>EntityExistsException</code>.</p>
  
  <p>The only way I've found to make this work is:</p>
  
  <pre><code>customer.company = em.merge(customer.company);
  em.persist(customer);
  </code></pre>
  
  <p>but I'm looking for a generalized solution since I have dozens of entities like <code>Customer</code> and their JAX-RS resources extend an abstract resource where I don't know what to merge/set before persist the entity.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Same problem when try to merge two unserialized objects with a reference to the same entity, e.g.</p>
  
  <pre><code>{
      "id": "Cust0001",
      "company": {
          "id": "Comp1"
       },
       relatedCustomer: {
          "id": "Cust9999",
          "company": {
             "id": "Comp1"
          }
       }
  }
  </code></pre>
  
  <p>merging this also throws an <code>EntityExistsException</code> regarding <code>Company#Comp1</code>.</p>