我的数据库中有以下表格:
statement:
id | created_date | message
和
statement_configuration
id | name | currency
和
statement_balances
statement_id | statement_configuration_id | balance
statement_balances
表在statement_id
和statement_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注释构建此地图?
答案 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;
}
以这种方式创建的数据库表与问题中的数据库表相同。