如何在数据库中存储 Map<String,BigDecimal>



我有一个实体账户,应该有带有余额(Bigdecimal(的货币映射

我怎么能存储这样的信息,我想我需要一个单独的表,其中包含外国密钥帐户id,任何建议都将不胜感激,我只是在学习,谢谢

@Table(name = "account")
public class Account {
@Id
@GeneratedValue(strategy = AUTO)
@Column(name = "account_id")
private Long accountId;
@Column(name = "customer_id")
private Long customerId;
// ->> account  should contain the map bellow or foreign key to another table
//Map<String, BigDecimal> balances;
}

尝试以下操作:

@ElementCollection
@CollectionTable(name = "balances_mapping", 
joinColumns = {@JoinColumn(name = "account_id", referencedColumnName = "balance_id")})
@MapKeyColumn(name = "account_id")
@Column(name = "balances")
private Map<String, BigDecimal> balances;

或者使用联接表

@ElementCollection
@Immutable
@MapKeyColumn(name = "ACCOUNT")
@Column(name = "ACCOUNT_BALANCE")
@JoinTable(name = "ACCOUNT_BALANCES", joinColumns = @JoinColumn(name = "ACCOUNT_ID"))
private Map<String, BigDecimal> accounts;
create table ACCOUNT (
ACCOUNT_ID NUMBER not null  constraint FR_ACCOUNT_PK primary key,
)
create table ACCOUNT_BALANCE  (
ACCOUNT_ID      NUMBER        not null constraint  FK_ACCOUNT_ID references ACCOUNT,
ACCOUNT_NAME    VARCHAR2(100) not null,
ACCOUNT_BALANCE NUMBER(100) not null
)

你好,也许您的数据模型是错误的。

你是否尝试将你的地图更改为类似于另一个实体的列表,其中包含2个字段货币和余额

这将使您的代码更加清晰,以后您将能够向该实体添加其他值。

@Table()
public class Balance{
private String currency;
private BigDecimal balanceAmount
}

如果有时你需要使用地图给出的属性,你可以使用Stream来做这样的事情。

account.getBalances().stream().collect(Collectors.toMap(Balance::getCurrency, Balance::getBalanceAmount)

相关内容

最新更新