java - @ManyToOne 与连接表的关系(可为空 = false)
问题描述
尝试@ManyToOne
在单独的表中创建关系TestEntity
并TestAttr
获取错误响应:
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)
解决方案
我想你应该喜欢这个例子。如果您想将那里写的内容应用到您的项目中,您的实体可能如下所示:
测试实体
@Entity
public class TestEntity {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private TestAttr testAttr;
...
测试属性
@Entity
public class TestAttr {
@Id
@GeneratedValue
private Long id;
...
使用 Spring Data 存储库进行持久化的示例:
TestAttr attr = new TestAttr();
testAttrRepository.save(attr);
TestEntity entity1 = new TestEntity();
TestEntity entity2 = new TestEntity();
entity1.setTestAttr(attr);
entity2.setTestAttr(attr);
testEntityRepository.save(entity1);
testEntityRepository.save(entity2);
表
正如您现在所看到的,TestEntity 在数据库中具有它的 testAttr 的 ID:
注意这是单向的 OneToMany 关系。(TestEntity 引用了它的 testAttr,但 TestAttr 没有它的 testEntities 的列表,
您可以根据需要使用级联类型来调节 repo 方法的行为。希望我有所帮助:)
推荐阅读
- c# - 物体卡在 Navmesh 表面的边缘
- ios - 如何使用 Swift 5 从 Firebase 的快照中保存数据?
- python - 使用 BeautifulSoup 在网页上查找特定文本?
- purescript - 在 Purescript 中使用 Data.String.Regex(正则表达式)
- google-cloud-platform - GCP 实例元数据未通过范围
- xml - 如何定义具有无限最大值的元素
- typescript - 从函数重载签名中的对象值推断键类型
- junit5 - PiTest无缘无故“改变条件边界突变存活”?
- c# - 无法捕获 DbUpdateConcurrencyException
- laravel - 如何在 Laravel 中实现/执行“加载更多”或“查看更多”