简体   繁体   English

如果未用于DDL生成,则Hibernate @JoinColumn(nullable = false)是否冗余?

[英]Is Hibernate @JoinColumn(nullable = false) redundant if not used for DDL generation?

Some of our entities declare OneToMany / OneToOne Relationships with nullable = false 我们的某些实体使用nullable = false声明OneToMany / OneToOne关系

@OneToMany
@JoinColumn(name = "FK_ID", referencedColumnName = "ID", nullable = false)
private List<Things> manyThings;

We use Flyway for DDLs. 我们将Flyway用于DDL。 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? 我在许多资料中都读到JoinColumn属性为nullable仅用于DDL生成-那么我是否正确理解,当我们的Flyway脚本直接在DB上生成具有约束的表时,实体上的nullable = false属性是否多余? What exactly is meant by DDL-Generation and what does Hibernate offer in this regard? DDL-Generation的确切含义是什么?Hibernate在这方面提供什么?

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. 我遇到了这个问题,因为事实证明,在某些表上,对DB列的约束是Non-Null = true而在Java实体上,设置了属性nullable = false This didn't seem to have any effect on the application at runtime; 这似乎对运行时的应用程序没有任何影响。 it would happily insert null values. 它会很高兴地插入null值。 However, when running a SpringBootTest it would fail with a constraint violation. 但是,当运行SpringBootTest时,它将因约束冲突而失败。

It's not only for DDL generation, but also for Hibernate validation annotations. 它不仅用于DDL生成,而且还用于Hibernate验证批注。

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. 当您说nullable = false时 ,JPA会生成数据库约束(非null),并且ALSO会生成JSR 303 Bean验证 ,如果在运行时中nullable = false列为 null时,该验证将不允许您持久化实体。 So, when you write nullable = false , JPA generates those two features for the price of one. 因此,当您编写nullable = false时 ,JPA会以一个价格生成这两个功能。 @Column(nullable = false) is the JPA way of declaring a column to be not-null. @Column(nullable = false)是将列声明为非空的JPA方法。

With nullable = false, the following save shall fail: 如果nullable = false,则以下保存将失败:

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. JPA将抛出此异常,而不是让数据库发现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM