如何使用Hibernate正确映射MonetaryAmount?

时间:2019-02-19 14:12:45

标签: hibernate hibernate-mapping

当我尝试将自定义Expenditure对象映射到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;
...
}

在这种情况下如何执行映射?

2 个答案:

答案 0 :(得分:0)

您不能直接映射MonetaryAmount。

您可以尝试将其映射到BigDecimal,然后在代码中执行转换,也可以尝试实现Hibernate自定义类型(尝试搜索{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet", "SuperSecret": "I love Azure Functions", "EventHubConnectionString": "Endpoint=sb://jeffs.servicebus.windows.net/;SharedAccessKeyName=MyFakeKey;SharedAccessKey=NotARealSecret" } } ,或使用JPA转换(如果JPA为2.1或更高版本) 。answer在这个主题上有一些不错的链接。

答案 1 :(得分:0)

您可以使用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) {...}
}