title: How to deserialize Hibernate entity from JSON (Jackson) without creating DTO object
body: <p>I have a webapp that has been using Hibernate for persistence. Recently, a requirement was added that would require us to recieve entities over JSON deserialize them, then persist them.</p>
  
  <p>The problem lies in that the entity class uses Hibernate's object references for <code>@ManyToOne</code> relationships. For instance, my entity object looks like this (fake example):</p>
  
  <pre class="lang-java prettyprint-override"><code>public class Student {
      @Id private int student_id;
      @Column private String name;
      @ManyToOne private School school;
      @OneToMany private List&lt;Assignment&gt; assignments;
  }
  
  public class School {
      @Id private int school_id;
      @Column private String name;
  }
  
  public class Assignment {
      @Id private int assignment_id;
      @Column private String name;
      @Column private int grade;
  }
  
  </code></pre>
  
  <p>My <code>Student</code> table has columns <code>student_id</code>, <code>name</code>, and <code>school_id</code>. My <code>Assignment</code> table has columns <code>assignment_id</code>, <code>name</code> and <code>grade</code>.</p>
  
  <p>However, I'm not sure how to structure the JSON to send to the server. Let's say I am trying to create a new Student, with new Assignments, enrolled in an existing School.</p>
  
  <p>Ideally, the JSON should look like:</p>
  
  <pre class="lang-js prettyprint-override"><code>{
      "name": "vikarjramun",
      "age": 23,
      "school_id": 1893,
      "assignments": [
          { "name": "Math", "grade": 100 },
          { "name": "Science", "grade": 93 }      
      ]
  }
  </code></pre>
  
  <p>However, if I use Jackson on the current entities, the JSON must be structured as follows:</p>
  
  <pre class="lang-js prettyprint-override"><code>{
      "name": "vikarjramun",
      "age": 23,
      "school": { "school_id": 1983 }
      "assignments": [
          { "name": "Math", "grade": 100 },
          { "name": "Science", "grade": 93 }      
      ]
  }
  </code></pre>
  
  <p>When I try to persist the resultant object, it will then complain that the School already exists in the database (ConstraintViolationException).</p>
  
  <p>I don't mind changing the format of the JSON, I just want to somehow get an object that can be directly persisted into the database. Will I need to write a custom deserializer? How else can I accomplish this?</p>
  
  <p>Thanks</p>