java - @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”不能为空
我怎样才能避免冲突
解决方案
您的映射是双向的,因此您还必须以这种方式维护它:
A newA = new A()
B newB = New B()
newB.setProperties().....
newA.setB(newB);
// add this:
newB.setA(newA);
aRepository.save(newA);
推荐阅读
- django - 无法调用 ModelManager 中的函数
- mysql - 使用不同的参数重复 SQL 查询
- c++ - 模板特化:参数不同于 T 的成员函数
- ios - IPA 文件临时分发 - 无法安装应用程序
- c# - C#如何获取Firefox的当前url
- python - Seaborn.distplot 绘图不准确
- excel-formula - excel帮助 - 将数据转换成3列
- java - 为什么在迭代一个具有多个值的桶的情况下调用一次 hashCode() ?
- google-chrome - Chrome 45 NPAPI 插件优先级
- mysql - [FireDac][Phys][MySql]使用不支持的缓冲区类型:253(参数:2)