[英]Embeddable entity with @OneToOne attribute
我最近需要 map 来自嵌入式实体的一对一实体:
@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时,真正发生的是 hibernate更新实体 C 并将 a_id 字段设置为 null 。 这导致对象 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 的信息并保持正确的行为?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.