Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between @ManyToOne(optional=false) vs. @Column(nullable=false)

In JPA, I am confused when to use the attribute optional=false and the annotation @Column(nullable=false). What is the difference?

like image 405
Truong Ha Avatar asked Jul 26 '10 02:07

Truong Ha


People also ask

What does the annotation @basic optional false mean?

It means, if you try to persist an entity with a null field it will throw an exception if it is marked as optional=false (without contacting the database) and the entity will not be added to the JPA persistence context.

What does nullable false mean?

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.

What is optional false in hibernate?

1. optional=false is not working if you try to save the Personne without Adresse : "org.hibernate.PropertyValueException: not-null property references a null or transient value: " – Grégory. Nov 28, 2013 at 18:30. optional = false means that... the address is not optional.

What is nullable true in hibernate?

Hibernate doesn't perform any validation if you annotate an attribute with @Column(nullable = false). This annotation only adds a not null constraint to the database column, if Hibernate creates the database table definition. The database then checks the constraint, when you insert or update a record.


2 Answers

@Column(nullable=false) is an instruction for generating the schema. The database column generated off the class will be marked not nullable in the actual database.

optional=false is a runtime instruction. The primary functional thing it does is related to Lazy Loading. You can't lazy load a non-collection mapped entity unless you remember to set optional=false (because Hibernate doesn't know if there should be a proxy there or a null, unless you tell it nulls are impossible, so it can generate a proxy.)

like image 80
Affe Avatar answered Sep 20 '22 01:09

Affe


Both is used to prevent a null value, but if you mind that null should be blocked in ...

The database layer (and you want to generate the schema using JPA) --> use @Column(nullable=false)

The runtime (and before contacting the database)--> use optional=false (much faster than the first checking).

If you want both abilities, use them both.

like image 33
O.Badr Avatar answered Sep 21 '22 01:09

O.Badr