java - 验证货币代码与允许值之一匹配

标签 java validation java-money jsr354

我有一个 POJO,其中包含一个名为 price 的字段。

该字段的类型是 javax.money.MonetaryAmount,这样我就可以从 JSR 354 验证等中受益。

我对指定货币必须是 EUR 的字段有一个限制:

@Currency("EUR")

如何指定货币必须是 EURUSD

import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.validator.constraints.Currency;
import org.jadira.usertype.moneyandcurrency.moneta.PersistentMoneyAmountAndCurrency;

import javax.money.MonetaryAmount;
import javax.persistence.*;

@Entity
@TypeDef(name = "persistentMoneyAmountAndCurrency", typeClass = PersistentMoneyAmountAndCurrency.class)
public class LocalizedProduct {

    @Id
    @GeneratedValue
    private long id;

    @Currency("EUR")
    // @Currency("EUR, USD") .. doesn't work
    @Columns(columns = {
            @Column(name = "amount_currency", length = 3),
            @Column(name = "amount_value", precision = 19, scale = 5)})
    @Type(type = "persistentMoneyAmountAndCurrency")
    private MonetaryAmount price;

    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public MonetaryAmount getPrice() {
        return this.price;
    }

    public void setPrice(MonetaryAmount price) {
        this.price = price;
    }
}

最佳答案

注解支持String[]作为value:https://github.com/hibernate/hibernate-validator/blob/master/engine/src/main/java/org/hibernate/validator/constraints/Currency.java

虽然您可以简单地使用 @Currency({"EUR", "USD"})

关于java - 验证货币代码与允许值之一匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66422235/

相关文章:

java - 在 POJO 类中定义 JSON 映射所需的字段

java-money - 使用 JSR-354 ExchangeRates 阻止应用程序退出

java - 使用 hibernate 4.0 和 spring 3.1.0.release 的事件监听器?

php - Nette Forms Validation - 如何设置不需要的字段?

jQuery Validate,确定是否选择了特定的单选元素,然后需要文本输入,无需 ID

OSGI 中的 Java 货币引用实现

java - GridBagLayout gridwidth 不能按预期工作

java - 案例期间的成绩簿循环

java - 使用 OneToOne 映射的 Spring Boot 2 自定义查询