1

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.

Roberto Rodriguez
  • 3,179
  • 32
  • 31
  • You should use `ManyToOne(optional = true)` for Dealer and User – Md Zahid Raza Sep 02 '16 at 16:48
  • you can also consider using ManyToAny mapping [link](http://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#mapping-column-any) – Md Zahid Raza Sep 02 '16 at 17:02
  • Maybe this blog can help you https://stackoverflow.com/questions/25718229/can-a-manytoone-jpa-relation-be-null – kenu8 Jul 09 '19 at 18:36

0 Answers0