首页 > 解决方案 > 保存辅助实体时如何保持 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 的外键?

标签: jpaspring-data-jpapersistenceone-to-one

解决方案


最简单的解决方案是这样的:

EntityA a = new EntityA();
EntityB b = new EntityB();
b.setEntityBField(a);
entityARepository.save(a)

您需要做的唯一更改是以下行:

b.setEntityBField(a);

推荐阅读