首页 > 解决方案 > @ManyToOne 与连接表的关系(可为空 = false)

问题描述

尝试@ManyToOne在单独的表中创建关系TestEntityTestAttr获取错误响应:

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)

标签: javamysqldatabasehibernatejdbc

解决方案


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


测试实体

@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 方法的行为。希望我有所帮助:)


推荐阅读