Jpa 保存辅助实体时如何保持oneToOne关系
我使用的是SPRING数据JPA,我有以下实体:Jpa 保存辅助实体时如何保持oneToOne关系,jpa,spring-data-jpa,persistence,one-to-one,Jpa,Spring Data Jpa,Persistence,One To One,我使用的是SPRING数据JPA,我有以下实体: public class EntityA { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SOME_SEQ") @SequenceGenerator(sequenceName = "SOME_SEQ", allocationSize = 1, name = "SOME_SEQ&q
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为null。
您能建议我如何持久化将EntityB链接到EntityA的外键吗?您需要实现方法EntityA.setEntityB,如下所示:
public class EntityA {
public void setEntityB(EntityB entityB) {
if (entityB == null) {
if (this.entityB != null) {
this.entityB.setEntityBField(null);
}
}
else {
entityB.setEntityBField(this);
}
this.entityB = entityB;
}
}
EntityA a = new EntityA();
EntityB b = new EntityB();
b.setEntityBField(a);
entityARepository.save(a)
EntityB.SetEntityB字段应为常用设置器:
public class EntityB {
public void setEntityBField(EntityA entityBField) {
this.entityBField = entityBField;
}
}
此外,注释中可能需要“optional=false”:
@OneToOne(mappedBy = "entityBField", cascade = CascadeType.ALL, optional = false)
private EntityB entityB;
请参见本文中的示例:
注意:
mappedBy=“entityBField”
表示
EntityB.entityBField
负责管理一对一关系
因此,当您创建EntityB=new EntityB()
并设置a.setEntityB(b)
时,当您进行级联保存时,b.entityBField
为空:entityARepository.save(a)
这就是为什么b.entityBField
(外键“entitya\u Id”)在数据库中为空
通过在EntityA中实现正确的setter,您可以帮助JPA理解,
entityB.entityBField
应该设置为EntityA的主键(entityB.setEntityBField(this)
)最简单的解决方案如下:
public class EntityA {
public void setEntityB(EntityB entityB) {
if (entityB == null) {
if (this.entityB != null) {
this.entityB.setEntityBField(null);
}
}
else {
entityB.setEntityBField(this);
}
this.entityB = entityB;
}
}
EntityA a = new EntityA();
EntityB b = new EntityB();
b.setEntityBField(a);
entityARepository.save(a)
您需要做的唯一更改是以下行:
b.setEntityBField(a);