gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:44:10 24 4
gpt4 key购买 nike

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

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> 类型的 map 在我的里面Statement实体。该 map 将映射statement_configuration_idbalance ;让我获得所有 StatementBalance链接到此 Statement (由 statement_configuration_id 键入)。

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

最佳答案

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

@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;
}

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

关于java - 使用复合主键从另一个表构建映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34161950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com