spring 如何使用Hibernate正确MapMonetaryAmount?

xfb7svmp  于 12个月前  发布在  Spring
关注(0)|答案(3)|浏览(104)

当我试图将我的自定义支出对象Map到MySQL中的关系模型时,我得到了错误:

Initial SessionFactory creation failed.org.hibernate.MappingException: Could not determine type for: javax.money.MonetaryAmount, at table: Expenditure, for columns: [org.hibernate.mapping.Column(monetaryAmount)]

字符串
我的支出类别:

@Entity
public class Expenditure implements Comparable<Expenditure> {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String description;

    private MonetaryAmount monetaryAmount;

    private LocalDate date;

    private ExpenditureType type;

    @OneToOne
    private User client;
...
}


在这种情况下如何执行Map?

5cg8jx4n

5cg8jx4n1#

你可以使用jpa'2 @Convert注解:

@Convert(converter = MonetaryAmountConverter.class)
private MonetaryAmount monetaryAmount;

字符串
然后像这样实现它:

@Converter
public class MonetaryAmountConverter implements AttributeConverter<MonetaryAmount, BigDecimal> {

    @Override
    public BigDecimal convertToDatabaseColumn(MonetaryAmount attribute) {...}

    @Override
    public MonetaryAmount convertToEntityAttribute(BigDecimal dbData) {...}
}

fcg9iug3

fcg9iug32#

您不能直接MapMonetaryAmount。
您可以尝试将其Map到BigDecimal,然后在代码中执行转换,或者您可以尝试实现Hibernate自定义类型(尝试搜索@Type,或使用JPA转换(如果JPA是2.1或更高版本)。

j2datikz

j2datikz3#

如果您还需要存储货币,那么您应该使用Vlad Mihalceas https://github.com/vladmihalcea/hypersistence-utils

@CompositeType(MonetaryAmountType.class)
private MonetaryAmount amount;

字符串
该数据库应包含金额和货币:

<column name="amount" type="decimal(19,4)"/>
<column name="currency" type="char(3)"/>


如果你需要不同的名称(例如,当你的表中有多个金额时),那么就选择@ AttributeName:

@AttributeOverride(name = "amount", column = @Column(name = "amount_in_question"))
@AttributeOverride(name = "currency", column = @Column(name = "amount_in_question_currency"))
@CompositeType(MonetaryAmountType.class)
private MonetaryAmount amountInQuestion;

相关问题