mysql - 将 Money 持久化到数据库中。设计决策

标签 mysql database-design currency

我需要一个表来存储金融交易的状态。 这个交易的状态可以通过这个类来大致建模。

class FinancialTransaction
{
    Integer txId,
    Money oldLimit,
    Money newLimit,
    Money oldBalance,
    Money newBalance,
    Date txDate
}
class Money
{   
    Currency curr,
    BigDecimal amount
}

我的架构初始设计如下所示:

CREATE TABLE tx
(
    txId bigint(20) unsigned NOT NULL,
    oldlimit_currency varchar(3) NULL,
    oldlimit_amount decimal(7,5) default 0.00,
    newlimit_currency varchar(3) NULL,
    newlimit_amount decimal(7,5) default 0.00,
    ----snipped----
    PRIMARY KEY (txId)
)

有两件事让我担心:

  1. 每笔交易都基于一种货币。关于我是否需要支持可能以多种货币进行的交易,我还没有想得很远。假设它没有改变;那么只维护一个货币栏不是更节省空间吗?我会后悔这个简单的解决方案吗?
  2. 由于每个 Money 项目都是一个值对象,我是否应该将所有 Money 对象保存到一个单独的 Money 表中,并让原始表使用 moneyIds 作为 Money 表的外键?

也就是说,

CREATE TABLE tx
(
    txId bigint(20) unsigned NOT NULL,
    oldlimit_money_id int NOT NULL,
    newlimit_money_id int NOT NULL,
    ----snipped----
    PRIMARY KEY (txId),
    FOREIGN KEY (oldlimit_money_id) REFERENCES MONEY(id) ON DELETE NO ACTION ON UPDATE NO ACTION,
    FOREIGN KEY (newlimit_money_id) REFERENCES MONEY(id) ON DELETE NO ACTION ON UPDATE NO ACTION
)

是否有替代设计?

感谢 lazyweb。

最佳答案

货币和货币值(value)是两个不同的概念,所以最好将它们分开。没有必要为“值(value)”制作单独的表格,但最好为货币制作一个表格,因为它们是独立的实体。新设计看起来像:

CREATE TABLE tx
(
    id bigint(20) unsigned primary key,
    old_limit_currency_id int not null references CURRENCY(id),
    old_limit_value decimal(7,5) not null,
    new_limit_currency_id int not null references CURRENCY(id),
    new_limit_value decimal(7,5) not null
)

此外,检查 decimal(7,5) 是否有足够的空间用于您的场景,它看起来有点低。有句老话:“安全胜于遗憾”:)

关于mysql - 将 Money 持久化到数据库中。设计决策,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/427362/

相关文章:

mongodb - 从 Categories MySQL 表到 MongoDB 设计

java - 具有多个条目的属性的数据库表设计(例如 : Person -> Social Media)

character-encoding - 英镑符号在商店中显示为未知字符

java - 我怎样才能找到 BlackBerry 上的系统默认货币符号?

ios - 在发薪日应用程序中为货币添加逗号

java - JPA 不按 LocalDate 和 LocalTime 对记录进行排序

mysql - 插入时为什么闭包表指向自身

mysql - 创建具有可查看历史记录的数据库条目?

php - 是否可以运行 PHP exec() 但从进程列表中隐藏参数?

sql - 设计此特定数据库/SQL 问题的最佳方法是什么?