In JPA, I am confused when to use the attribute optional=false
and the annotation @Column(nullable=false)
. What is the difference?
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.
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. 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.
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.
@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.)
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.
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