title: Always use primitive object wrappers for JPA @Id instead of primitive type?
body: <p>I've found the issue with using primitive type as an object @Id for JPA in conjunction with Spring Data JPA.
  I have parent/child relationship with Cascade.ALL on the parent side, and child has PK which at the same time is also parent's FK.</p>
  
  <pre><code>class Parent {
      @Id
      private long id;
  
      @OneToOne(mappedBy = "parent", cascade = ALL)
      private Child child;
  }
  
  class Child {
      @Id
      @OneToOne
      private Parent parent;
  }
  </code></pre>
  
  <p>So, when I run:</p>
  
  <pre><code>...
  Parent parent = new Parent();
  Child child  = new Child(parent);
  parent.setChild(child);  
  em.persist(parent)
  ...
  </code></pre>
  
  <p>everything works fine. But I used Spring Data JPA to persist the entity, so I run instead:</p>
  
  <pre><code>parentRepository.save(parent); // instead of em.persist(parent);
  </code></pre>
  
  <p>and this one was failed with the following exception:</p>
  
  <pre><code>Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: Parent
  </code></pre>
  
  <p>The problem was that Spring Data JPA <em>save()</em> method checks whether the entity is new, and if it is new then <em>em.persist()</em> is used otherwise <em>em.merge()</em> is used.</p>
  
  <p>The interesting part here how Spring checks whether the entity is new or not:</p>
  
  <pre><code>getId(entity) == null;
  </code></pre>
  
  <p>And, of course, this was false, because I used long as the type for @Id, and the default value for long is 0. When I changed long to Long everything works with Spring Data JPA also.</p>
  
  <p>So is it the recommended practice always to use object wrappers for the primitive types (like Long instead of long) instead of primitive types. Any 3rd party resource describing this as the recommended practice would be very nice.</p>