首页 > 解决方案 > 如何从同一个表映射多个@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

在上面的示例中,将有两行,uncertaintydata_field值为propertyApropertyB

这样的东西会很方便..

@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 映射的最佳方式是什么?

非常感谢。

标签: javadatabasehibernatejpa

解决方案


您所描述的是一个 OneToMany 关系,其中每个 Container 都有一个不确定性集合。

@Entity
class Container {
    @JoinColumn(name = "container_id")
    private Collection<Uncertainty> properties;
    ...
}

@Entity
class Uncertainty {
    ...
}

在不确定性中不需要额外的东西来映射它。


推荐阅读