Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the different between @ManyToOne optional flag vs @JoinColumn nullable flag?

Tags:

jpa

I have the following to define a Company which cannot be null on my entity:

@ManyToOne(optional = false)
@JoinColumn(nullable = false)
private Company company;

What is the difference between 'optional = false' on the @ManyToOne annotation and 'nullable = false' on the @JoinColumn annotation. Or is setting both of them redundant?

like image 943
dleerob Avatar asked Nov 02 '16 12:11

dleerob


People also ask

What is @manytoone optional false?

Description. This annotation will create a NOT NULL constraint on the column when it shouldn't. The JoinColumn configuration should override the default generated by "optional=false". This is relevant in single table inheritance situations.

What is optional in @manytoone?

Thus all relations of the actual entity specified with optional=false result in an INNER JOIN to their respective relation when loaded, whereas relations specified with optional=true result in LEFT JOINs.

What is nullable false in Hibernate?

The @Column(nullable = false) Annotation It's used mainly in the DDL schema metadata generation. This means that if we let Hibernate generate the database schema automatically, it applies the not null constraint to the particular database column.


1 Answers

@ManyToOne operates on the so called logical model, i.e. the object-oriented side of the object-relational mapping. The semantics of optional=false here are:

Whether the association is optional. If set to false then a non-null relationship must always exist.

So the JPA engine expects that the underlying storage will always provide a value that can be translated to a Company object.

@JoinColumn operates on the physical model, i.e. how things are actually laid down in the datastore (database). Specifying nullable = false will make the DB column non-nullable.

If @JoinColumn(nullable = false) was omitted, the column would be nullable. One could insert a null value there and the DB would happily accept it. However if someone tried to read that value through JPA, the JPA engine would protest because it expects a value that can be translated to a Company object to always be there, as specified by @ManyToOne(optional = false).

like image 178
Nikos Paraskevopoulos Avatar answered Sep 27 '22 23:09

Nikos Paraskevopoulos