gpt4 book ai didi

java - @ManyToOne 与连接表的关系(nullable = false)

转载 作者:行者123 更新时间:2023-11-29 17:02:29 24 4
gpt4 key购买 nike

尝试在 TestEntityTestAttr 之间的单独表中创建 @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)

最佳答案

我想你应该喜欢this例子。如果您想将其中写入的内容应用到您的项目中,您的实体可能如下所示:

<小时/>

测试实体

@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:

tables in database

注意这是一种单向 OneToMany 关系。 (TestEntity 引用了它的 testAttr,但是 TestAttr 没有它的 testEntities 列表

您可以根据需要使用级联类型来调节 repo 方法的行为。希望我有帮助:)

关于java - @ManyToOne 与连接表的关系(nullable = false),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52167712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com