java - 如何从同一个表映射多个@OneToOne 关联
问题描述
我目前有一个简单的应用程序,其中我的 Container 类的属性映射到数据库列。
今天...
@Entity
class Container {
@Column
private BigDecimal propertyA;
@Column
private BigDecimal propertyB;
}
我正在尝试扩展我的设计,以允许将每个逻辑属性的多个值存储在一起。我现在想为每个属性存储 5 个值来表示它们的不确定性(有些可能为空)
在数据库模式级别,这可以这样表示。我不相信每个不确定性都需要它自己的 id,因为 (container_id, data_field) 的组合是唯一的。
CREATE TABLE container (
id INT PRIMARY KEY,
...
);
CREATE TABLE uncertainty (
container_id bigint not null,
data_field varchar(100) not null,
maximum decimal null,
upside decimal null,
reference decimal null,
downside decimal null,
minimum decimal null,
primary key (container_id, data_field),
constraint fk_container_id foreign key (container_id) references container (id),
);
对于需要此功能uncertainty
的每个属性,表中将有一行。Container
在上面的示例中,将有两行,uncertainty
其data_field
值为propertyA
和propertyB
。
这样的东西会很方便..
@Entity
class Container {
// How do I map multiple @OneToOne relationships to the uncertainty table based on e.g. the value of data_field = 'propertyA' or data_field = 'propertyB'
private Uncertainty propertyA;
private Uncertainty propertyB;
}
@Entity
class Uncertainty {
// Do I need fields here to represent the composite primary key (containerId, data_field)?
@Column
private BigDecimal maximum;
@Column
private BigDecimal upside;
@Column
private BigDecimal reference;
@Column
private BigDecimal downside;
@Column
private BigDecimal minimum;
}
将这种关系与 JPA/Hibernate 映射的最佳方式是什么?
非常感谢。
解决方案
您所描述的是一个 OneToMany 关系,其中每个 Container 都有一个不确定性集合。
@Entity
class Container {
@JoinColumn(name = "container_id")
private Collection<Uncertainty> properties;
...
}
@Entity
class Uncertainty {
...
}
在不确定性中不需要额外的东西来映射它。
推荐阅读
- reactjs - 在 react-three-fiber 添加three.js
- javascript - 如何正确地将 React 注入 content.js Chrome 扩展
- reactjs - 深度链接 - 如何从 React 打开深度链接
- .net - 如何将 Postgres 设置为 Hyperledger Aries DotNet 调解器的数据库
- matlab - Rodrigues 公式将旋转向量转换为旋转矩阵
- oozie - Oozie 让其他分叉操作继续,以防一个失败但在加入后终止
- angular - 使用大量子组件优化 Angular 组件
- hibernate-search - 如何在休眠搜索中查询空集合
- javascript - 如何将以下字符串拆分为可用于填充 html 表的数组
- clang - 如何使用 c++ API 获取与 ClangAST 中的节点关联的指针?