Some of our entities declare OneToMany
/ OneToOne
Relationships with nullable = false
@OneToMany
@JoinColumn(name = "FK_ID", referencedColumnName = "ID", nullable = false)
private List<Things> manyThings;
We use Flyway for DDLs. I have read in many sources that the JoinColumn
property nullable
is only used for DDL generation - so do I understand correctly that when our Flyway Scripts generate Tables with Constraints on the DB directly, the nullable = false
property on our Entities is redundant? What exactly is meant by DDL-Generation and what does Hibernate offer in this regard?
I came across this problem because on some tables it turned out that the constraint on the DB Columns were Non-Null = true
whereas on the Java Entities the property nullable = false
was set. This didn't seem to have any effect on the application at runtime; it would happily insert null
values. However, when running a SpringBootTest it would fail with a constraint violation.
It's not only for DDL generation, but also for Hibernate validation annotations.
When you say nullable = false , JPA generates database constraints (not-null) and ALSO generate a JSR 303 Bean Validation that don't let you persist the entity if the nullable = false column is null in Runtime. So, when you write nullable = false , JPA generates those two features for the price of one. @Column(nullable = false) is the JPA way of declaring a column to be not-null.
With nullable = false, the following save shall fail:
ObjectThatContainsListThings a = new ObjectThatContainsListThings();
a.setListOfThings(null)
hibernate.persist(a);
DataIntegrityViolationException: not-null property references a null or transient value
JPA will throw this exception instead of letting the database find the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.