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?
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.
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.
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.
@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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With