简体   繁体   English

使用 Spring Data JDBC 持久化资金

[英]Persisting Money with Spring Data JDBC

Let's take a following entity:让我们以以下实体为例:

class Item{
    @Id
    Long id;
    String name;
    org.joda.money.Money price;
}

and a corresponding repository:和相应的存储库:

interface ItemRepository extends CrudRepository<Item, Long> {
}

Is it possible to persist Item in a relational DB table having amount and currency in separate columns without manually rewriting SQL queries offered by ItemRepository ?是否可以在不手动重写ItemRepository提供的 SQL 查询的情况下,将 Item 保存在具有单独列中的金额和货币的关系数据库表中?

DDL could be something like: DDL 可能是这样的:

CREATE TABLE ITEM (
    ID             INTEGER IDENTITY NOT NULL,
    NAME           VARCHAR(255)     NULL,
    PRICE_AMOUNT   DECIMAL          NULL,
    PRICE_CURRENCY VARCHAR(3)       NULL
);

Storing Money in a single VARCHAR column using custom @WritingConverter and @ReadingConverter is the closest I got, however this is not an option, as I need amount and currency clearly separated at the DB level.使用自定义@WritingConverter@ReadingConverter将 Money 存储在单个VARCHAR列中是我得到的最接近的,但这不是一个选项,因为我需要在 DB 级别明确分开金额和货币。

I'm fine with replacing joda.money in favor of javax.money if that makes a difference, however I do not want to introduce my own custom type for handling money in domain layer.如果这有所不同,我可以替换joda.money以支持javax.money ,但是我不想引入我自己的自定义类型来处理域层中的资金。

There are the following options available to persist properties of non standard types in Spring Data JDBC有以下选项可用于在 Spring Data JDBC 中持久化非标准类型的属性

  1. Use @WritingConverter and @ReadingConverter in order to convert the value to something Spring Data JDBC knows.使用@WritingConverter@ReadingConverter将值转换为 Spring Data JDBC 知道的值。 You already discovered that this works only with single columns您已经发现这仅适用于单列

  2. You can mark it as an @Embedded which will convert each attribute to a column.您可以将其标记为@Embedded ,它将每个属性转换为一列。 I'm not sure if Money has suitable attributes but it is lacking a suitable constructor so this doesn't work either.我不确定Money是否具有合适的属性,但它缺少合适的构造函数,因此这也不起作用。

  3. Use a different type that you can handle with one of the first approaches.使用可以通过第一种方法处理的不同类型。 In this case this would mean write your own Money type which has a suitable constructor and attributes to work as an embedded.在这种情况下,这意味着编写您自己的Money类型,该类型具有合适的构造函数和属性以作为嵌入式工作。

  4. Tweak your database: you can create a view which uses a single column representation and stores it as a single column.调整您的数据库:您可以创建一个使用单列表示并将其存储为单列的视图。 It might still make it available as separate columns for sorting and filtering.它可能仍然可以将其作为单独的列用于排序和过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM