What's the difference between @Basic(optional = false)
and @Column(nullable = false)
in JPA persistence?
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.
179: @Basic(optional = false) @Column(nullable = false) The @Basic annotation marks the property as not optional on the Java object level. The second setting, nullable = false on the column mapping, is only responsible for the generation of a NOT NULL database constraint.
optional=false is a runtime instruction. The primary functional thing it does is related to Lazy Loading.
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.
Gordon Yorke (EclipseLink Architecture Committee Member, TopLink Core Technical Lead, JPA 2.0 Expert Group Member) wrote a good answer on this topic so instead of paraphrasing him, I'll quote his answer:
The difference between
optional
andnullable
is the scope at which they are evaluated. The definition of 'optional
' talks about property and field values and suggests that this feature should be evaluated within the runtime. 'nullable
' is only in reference to database columns.If an implementation chooses to implement
optional
then those properties should be evaluated in memory by the Persistence Provider and an exception raised before SQL is sent to the database otherwise when using 'updatable=false
' 'optional
' violations would never be reported.
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