[英]@OneToOne(optional=false) and @JoinColumn(nullable=false) used together
[英]Is Hibernate @JoinColumn(nullable = false) redundant if not used for DDL generation?
我们的某些实体使用nullable = false
声明OneToMany
/ OneToOne
关系
@OneToMany
@JoinColumn(name = "FK_ID", referencedColumnName = "ID", nullable = false)
private List<Things> manyThings;
我们将Flyway用于DDL。 我在许多资料中都读到JoinColumn
属性为nullable
仅用于DDL生成-那么我是否正确理解,当我们的Flyway脚本直接在DB上生成具有约束的表时,实体上的nullable = false
属性是否多余? DDL-Generation的确切含义是什么?Hibernate在这方面提供什么?
我遇到了这个问题,因为事实证明,在某些表上,对DB列的约束是Non-Null = true
而在Java实体上,设置了属性nullable = false
。 这似乎对运行时的应用程序没有任何影响。 它会很高兴地插入null
值。 但是,当运行SpringBootTest时,它将因约束冲突而失败。
它不仅用于DDL生成,而且还用于Hibernate验证批注。
, JPA generates database constraints (not-null) and ALSO generate a JSR 303 Bean Validation that don't let you persist the entity if the column is null in Runtime. 当您说 ,JPA会生成数据库约束(非null),并且ALSO会生成JSR 303 Bean验证 ,如果在运行时中 null时,该验证将不允许您持久化实体。 , JPA generates those two features for the price of one. 因此,当您编写 ,JPA会以一个价格生成这两个功能。 is the JPA way of declaring a column to be not-null. 是将列声明为非空的JPA方法。
如果nullable = false,则以下保存将失败:
ObjectThatContainsListThings a = new ObjectThatContainsListThings();
a.setListOfThings(null)
hibernate.persist(a);
DataIntegrityViolationException: not-null property references a null or transient value
JPA将抛出此异常,而不是让数据库发现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.