首页 > 解决方案 > @OneTOOne 映射不保存 MySQL。JpaRepository

问题描述

我在一对一关系中有两个模型,但是当尝试保存它时提供 ID 错误,

@Entity
@Table(name = "app_a_table")
class A {
    
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    ...

    @OneToOne(mappedBy = "a", cascade = CascadeType.ALL)
    private B b;

    ...
    // Constructor
    // Getter & Setter
}

@Entity
@Table(name = "app_b_table")
class B {
    
    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    ...

    @OneToOne()
    @JoinColumn(name = "A_ID", referencedColumnName = "ID")
    private A a;

    ...
    // Constructor
    // Getter & Setter
}

当我尝试如下保存时

A newA = new A()
B newB = New B()

newB.setProperties().....

newA.setB(newB);

aRepository.save(newA);

抛出异常列“A_ID”不能为空

我怎样才能避免冲突

标签: javamysqlspringhibernatehibernate-mapping

解决方案


您的映射是双向的,因此您还必须以这种方式维护它:

A newA = new A()
B newB = New B()

newB.setProperties().....

newA.setB(newB);
// add this:
newB.setA(newA);

aRepository.save(newA);

推荐阅读