[英]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.