java - 具有@OneToOne 属性的可嵌入实体
问题描述
我最近需要从一个嵌入实体映射一个一对一的实体:
@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 字段设置为 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的信息并保持正确的行为?
推荐阅读
- c# - 使用反序列化 XML 文件中的多字段 List<> 填充第二个单字段列表 (Xamarin)
- java - JSON 在全选中抛出 java.lang.StackOverflowError
- c# - 在 C# 中使用 Python 库
- javascript - 用于处理日期选择器下拉列表的 JavaScript 对象(三个不同的下拉列表)
- webpack - Webpack 4 - 父文件夹中的 node_modules。如何创建供应商块?
- php - 如果使用 HTML,TCPDF MultiCell 会忽略 valign
- c# - RabbitMQ C# 客户端可扩展?
- apache-spark - Spark shuffle 阻止复制
- rest - 运行在不同 Docker 容器中的 Spring Boot 应用程序拒绝连接
- vim - 在 pipenv 中从 vim ALE 运行 Pylint 和 MyPy 时出现错误的导入错误。-- :!pylint % 有效 -- :!mypy % 有效