Jpa-2.0 – the @ manytoone relationship cannot be empty
I have a one-on-one relationship and I want to be free:
@ManyToOne(optional = true) @JoinColumn(name = "customer_id",nullable = true) private Customer customer;
Unfortunately, JPA sets the columns in the database to not null Can anyone explain? Is there a way to make it work? Please note that I use JBoss 7, JPA 2.0 and Hibernate as persistence providers and PostgreSQL 9.1 databases
Edit:
I found the cause of my problem Obviously, it is because I have defined the primary key customer in the reference entity:
@Entity @Table public class Customer { @Id @GeneratedValue @Column(columnDeFinition="serial") private int id; }
It seems that using @ column (columndefinition = "serial") as the primary key can automatically set the foreign key referencing it to not null in the database Is this really the expected behavior when specifying the column type as serial? Is there a solution to make nullable foreign keys in this case?
Thank you first
Solution
I found a solution to my problem The primary key is well defined in the entity customer. The problem is the foreign key declaration It should be declared that:
@ManyToOne @JoinColumn(columnDeFinition="integer",name="customer_id") private Customer customer;
In fact, if the attribute columndefinition = "integer" is omitted, the foreign key will default to the source column: a non empty sequence with its own sequence This is certainly not what we want, because we just want to reference the automatically incremented ID instead of creating a new ID
In addition, when performing some tests, it seems that I also need the attribute name = customer_ ID. otherwise, the foreign key column will still be set as the source column This seems to me to be a strange behavior Comments or additional information are welcome to clarify this matter!
Finally, the advantage of this solution is that the ID is generated by the database (not by JPA), so we don't have to worry about inserting data manually or in scripts that often occur in data migration or maintenance