问题描述
我最近需要从嵌入的实体映射一对一的实体:
@Entity
public class A {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Embedded
private B b;
//getters and setters
}
@Embeddable
public class B {
@OnetoOne(mappedBy="a",cascade = CascadeType.ALL,orphanRemoval = true)
private C c;
//getters and setters
}
@Entity
public class C {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OnetoOne
@JoinColumn(name="a_id")
private A a;
//other fields,getters and setters
}
当我们创建、更新实体 c 的信息并删除 a(并因此删除 c)时,此映射正常工作。
问题是当我们尝试通过更新删除C时,真正发生的是休眠更新实体C并将a_id字段设置为空。这导致对象 C 没有附加到任何实体 A。
解决方法
我的解决方法是在实体A中一对一复制关系的信息
@Entity
public class A {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Embedded
private B b;
@OneToOne(mappedBy="a",cascade = CascadeType.ALL,orphanRemoval = true)
private C c;
public void setB(final Optional<B> b) {
b.ifPresentOrElse(newB -> {
newB.getC().ifPresent(c -> {
c.setA(this);
this.b = b;
},() -> {
this.c = null;
this.b = null;
});
}
// other getters and setters
}
有没有办法不复制A中实体C的信息并保持正确的行为?