Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Basic(optional = false) vs @Column(nullable = false) in JPA

Tags:

java

orm

jpa

What's the difference between @Basic(optional = false) and @Column(nullable = false) in JPA persistence?

like image 984
joaosavio Avatar asked May 24 '10 17:05

joaosavio


People also ask

What is @column nullable false?

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 @basic optional false?

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.

What is optional false in JPA?

optional=false is a runtime instruction. The primary functional thing it does is related to Lazy Loading.

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.


1 Answers

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 and nullable 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.

like image 82
Pascal Thivent Avatar answered Oct 13 '22 14:10

Pascal Thivent