【发布时间】:2018-09-04 13:41:12
【问题描述】:
尝试在TestEntity 和TestAttr 之间的单独表中创建@ManyToOne 关系得到错误响应:
org.hibernate.PropertyValueException: not-null property references a null or transient value : com.test.TestEntity.testAttr; nested exception is javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value : com.test.TestEntity.testAttr
这是有问题的实体:
@Table(name = "test_table")
public class TestEntity{
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "test_attr_test_entity", joinColumns = {@JoinColumn(name = "test_entity_id", nullable = false, updatable = false)},
inverseJoinColumns = {@JoinColumn(name = "test_attr_id", nullable = false, updatable = false)})
private TestAttr testAttr;
.
.
.
}
当更改为@ManyToMany 时,它可以正常工作。
持久化代码:
testEntityRepository.save(testEntity)
【问题讨论】:
-
可能您正试图保留一个
TestEntity,其testAttr属性为null,但我们确实需要一个minimal reproducible example 来确定。另外,为什么要使用连接表来建立多对一关系?它是允许的,但它很少是好的形式。 -
实际上是的,我正在尝试保留一个没有 testAttr 的 TestEntity,并且默认情况下 @ManyToOne 关系应该是可选的。那么为什么我不能持久化一个带有 null testAttr 的 TestEntity 呢?
-
可以添加实体代码吗?
-
1.为什么要为 @ManyToOne 关系创建连接表。 2. 如果你真的想创建一个,那么你不能持久化TestEntity 为空的testAttr,因为你已经在
name = "test_attr_id", nullable = false,...3 中指定了它。也许只是写下你想要完成的事情,以便我们重新考虑并提供一些解决方案。 -
1.我需要另一个表,因为在大多数情况下不会有 testAttr,而且我不想要一个大部分为空值的列,2。我只想确保在表“test_attr_test_entity”中不允许空值。
标签: java mysql database hibernate jdbc