使用复合主键从另一个表构建映射

时间:2015-12-08 17:12:54

标签: java jpa

我的数据库中有以下表格:

statement:
id | created_date | message

statement_configuration
id | name | currency

statement_balances
statement_id | statement_configuration_id | balance

statement_balances表在statement_idstatement_configuration_id上有复合主键的位置。

我的Statement实体如下所示:

public class Statement implements Serializable {

  @Id
  private long id;

  @Column
  private String message

  //I'm not sure of which annotations I need here
  @OneToMany
  private Map<Long, StatementBalance> statementBalancesByConfigId;
  ....
}

StatementBalances实体如下所示:

public class Statement implements Serializable {

  @Id
  private long statmentId;

  @Id
  private long statementConfigurationId;

  @Column
  private long balance;
  ....
}

我的目标是在Map<Long, StatementBalances>实体中构建Statement类型的地图。地图会将statement_configuration_id映射到balance;允许我获取与此StatementBalance相关联的所有Statement(由statement_configuration_id键入)。

是否可以使用JPA注释构建此地图?

1 个答案:

答案 0 :(得分:1)

是的,这是可能的。一个示例解决方案:

@Entity
public class Statement implements Serializable {
    @Id
    private long id;

    private String message;

    @OneToMany(mappedBy = "statementId")
    @MapKey(name = "statementConfigurationId")
    private Map<Long, StatementBalances> statementBalancesByConfigId;
}
@Entity
@Table(name = "statement_configuration")
public class StatementConfiguration implements Serializable {
    @Id
    private long id;

    @OneToMany(mappedBy = "statementConfigurationId")
    private Collection<StatementBalances> statementBalances;

    private String name;
    private String currency;
}

StatementBalancesId复合主键类和StatementBalances实体类允许通过在它们之间创建两个双向关系来建模三元关联:

public class StatementBalancesId implements Serializable {
    long statementId;
    long statementConfigurationId;

    // requires no-arg constructor, equals, hashCode
}
@Entity
@Table(name = "statement_balances")
@IdClass(StatementBalancesId.class)
public class StatementBalances implements Serializable {
    @Id
    @ManyToOne
    @JoinColumn(name="statement_configuration_id")
    private StatementConfiguration statementConfigurationId;

    @Id
    @ManyToOne
    @JoinColumn(name="statement_id")
    private Statement statementId;

    @Column
    private long balance;
}

以这种方式创建的数据库表与问题中的数据库表相同。