【问题标题】:@OneTOOne Mapping not save MySQL. JpaRepository@OneTOOne 映射不保存 MySQL。 JpaRepository
【发布时间】:2020-11-21 23:05:42
【问题描述】:

我在一对一关系中有两个模型,但是当尝试保存它时提供 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”不能为空

如何避免冲突

【问题讨论】:

  • 坚持newB 或确保你cascade 是正确的
  • 请提供异常的堆栈跟踪

标签: java mysql spring hibernate hibernate-mapping


【解决方案1】:

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

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

newB.setProperties().....

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

aRepository.save(newA);

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    相关资源
    最近更新 更多