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

JavaHibernateOrmJpa

Java Problem Overview


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

Java Solutions


Solution 1 - Java

@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.)

Solution 2 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTruong HaView Question on Stackoverflow
Solution 1 - JavaAffeView Answer on Stackoverflow
Solution 2 - JavaO.BadrView Answer on Stackoverflow