title: JPA @one-to-many // rewrite stored ID
body: <p>I would like to rewrite the stored value for a <code>@ManyToOne</code> relationship before writing to the database to mimic the behaviour of some legacy code. Latter stores a unset relationship as <code>0</code> instead of <code>null</code>. All other values (&gt;0) are regular references.</p>
  <p>Is there a way to implement a custom mapping for the <code>@ManyToOne</code> value to handle this?</p>
  <p><strong>Entities:</strong></p>
  <pre><code>@Entity
  @Table(name = &quot;Content&quot;)
  public class ContentEntity
      // ..
      @ManyToOne(fetch = FetchType.EAGER)
      @JoinColumn(name = &quot;ColorID&quot;)
      private ColorEntity color;
  }
  
  @Entity
  @Table(name = &quot;Color&quot;)
  public class ColorEntity {
      @Id
      @GeneratedValue
      @Column(name = &quot;ID&quot;)
      private String id;
      // ..
  }
  
  </code></pre>
  <p><strong>Database:</strong></p>
  <pre><code>    CREATE TABLE `Content` (
          # ..
          `ColorID` VARCHAR(255) DEFAULT NULL);
      CREATE TABLE `Color` (
          `ID` VARCHAR(255) PRIMARY KEY,
          # ..)
  </code></pre>
  <p>There is no corresponding entry in the target table with <code>id:0</code> but multiple records for <code>id:&gt;0</code></p>
  <p>I'm using JPA in a Spring Boot application.</p>