title: JPA/Hibernate: How insert a default value for a @ManyToOne where the value represents a null entry
body: <p>I'm fairly new to JPA/Hibernate. My issue involves a couple of existing database tables as shown below:</p>
  
  <pre><code>CREATE TABLE `person` (
    `personId` int(11) NOT NULL,
    `name` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '',
    `addressId` int(11) NOT NULL DEFAULT 0,
    PRIMARY KEY (`personId`)
  );
  
  CREATE TABLE `address` (
    `addressId` bigint(20) NOT NULL,
    `address` varchar(255) CHARACTER SET latin1 NOT NULL DEFAULT '',
    PRIMARY KEY (`addressId`)
  );
  </code></pre>
  
  <p>The entities are implemented as such:</p>
  
  <pre><code>@Entity
  public class Person {
    @Id
    private Integer personId;
  
    private String name;
  
    @ManyToOne
    @JoinColumn(name="addressId")
    private Address address;
  }
  
  @Entity
  public class Address {
    @Id
    private Integer addressId;
  
    private String address;
  </code></pre>
  
  <p>}</p>
  
  <p>Multiple people can live in the same address. A person can also not have an address. The addressId from the person table is essentially an optional field.
  There is no addressId = 0 in the address database. The value 0 is basically used as if it was a null parameter.</p>
  
  <p>My issue is getting this to happen when I try to persist a person into table where the addressId = 0.</p>
  
  <p>If I set the Address object within the Person to null, I would get the following error:</p>
  
  <p>"addressId cannot be null"</p>
  
  <p>If I set the address object to have an addressId of 0, I get this other transientObjectError, which is returned because there's no entry in the address table with the addressId = 0.</p>
  
  <p>I tried using @PrePersist to try to attempt to set the default values before the object gets persisted, however, I get the same two errors above. Same thing when I add optional=true in the @ManyToOne.</p>
  
  <p>I don't think inserting an dummy address with id=0 is a good idea.</p>
  
  <p>Any ideas if it's possible to use the @ManyToOne annotation and still have a default value of 0 where 0 is not an actual entry in the database?</p>