jpa - 保存辅助实体时如何保持 oneToOne 关系
问题描述
我正在使用 SPRING DATA JPA,并且我有以下实体:
public class EntityA {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SOME_SEQ")
@SequenceGenerator(sequenceName = "SOME_SEQ", allocationSize = 1, name = "SOME_SEQ")
private Long id;
private String name;
@OneToOne(mappedBy = "entityBField", cascade = CascadeType.ALL)
private EntityB entityB;
}
public class EntityB {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SOME_OTHER_SEQ")
@SequenceGenerator(sequenceName = "SOME_OTHER_SEQ", allocationSize = 1, name = "SOME_OTHER_SEQ")
private Long id;
private Integer type;
@OneToOne
@JoinColumn(name = "entityaId", referencedColumnName = "id")
private EntityA entityBField;
}
这是表定义:
create table EntityA(
id int primary key,
name varchar(255)
);
create table EntityB(
id int primary key,
type int,
entitya_Id int FOREIGN KEY ("entitya_Id")
REFERENCES "EntityA" ("id")
);
我创建并保存一个实例如下:
EntityA a = new EntityA();
EntityB b = new EntityB();
a.setEntityB(b);
entityARepository.save(a)
发生的情况是 entityA 和 entityB 都被持久化,但 EntityB 上的外键 entityaId 为空。您能否建议我应该如何保留将 EntityB 链接到 EntityA 的外键?
解决方案
最简单的解决方案是这样的:
EntityA a = new EntityA();
EntityB b = new EntityB();
b.setEntityBField(a);
entityARepository.save(a)
您需要做的唯一更改是以下行:
b.setEntityBField(a);
推荐阅读
- java - 如何跳过读入文件上的字符串以获取后面的浮点数?
- unix - 将“/”附加到目录末尾
- node.js - 由于 componentDidMount() 在客户端运行时如何避免服务器端出错
- mysql - MySQL 存储过程仅在首次运行时返回结果
- powershell - 无法使用 SetEnvironmentVariable 设置 PATH
- c# - 使用 AJAX-ASP.NET MVC 5 在数据库中的表中删除包含图像和多个外键的行
- redirect - Safari IOS 13.1.2 上的特殊 PWA 错误
- java - 在 Java 中,使用 Scanner,有没有办法在 CSV 文件中查找特定字符串,将其用作列标题并返回其下的所有值?
- r - GCP 上的 RStudio Server Pro Standard 上的软件包安装时间异常长?
- swift - 当用户开始驾驶时获得通知 (CoreMotion)