This is my scenario, I have Cars, which belong either to a Dealer or a User (not both at the same time).
So my Car entity has a @ManyToOne relation with Dealer and User, but one of them needs to be null, so I added nullable=true in both, to support that.
This is my code:
@Entity
@Table(name = "car")
@XmlRootElement
public class Car implements Serializable{
@Id
@Column(name = "id", unique = true, nullable = false, columnDefinition = "serial")
@SequenceGenerator(name = "pk_sequence", sequenceName = "car_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence")
@Generated(GenerationTime.INSERT)
private Long id;
@ManyToOne
@JoinColumn(name = "dealer", nullable = true)
private Dealer dealer;
@ManyToOne
@JoinColumn(name = "user", nullable = true)
private User user;
But then when I try to insert a car without a Dealer I get this:
ERROR: null value in column "dealer" violates not-null constraint.
I understand that is because of a foreign key restriction generated by Hibernate in the database. But then: -What is the reason of having "nullable = true"? -How can I solve this problem where I need to have a @ManyToOne relationship and it can be null?
Thanks.