Search code examples
javaspringjpajava-8spring-data-jpa

How to properly map MonetaryAmount using Hibernate?


When I am trying to map my custom Expenditure object to relational model in MySQL, I got error:

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)]

My Expenditure class:

@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;
...
}

How can I perform mapping in this scenario?


Solution

  • You can use jpa'2 @Convert annotation:

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

    And then implement it like this:

    @Converter
    public class MonetaryAmountConverter implements AttributeConverter<MonetaryAmount, BigDecimal> {
    
        @Override
        public BigDecimal convertToDatabaseColumn(MonetaryAmount attribute) {...}
    
        @Override
        public MonetaryAmount convertToEntityAttribute(BigDecimal dbData) {...}
    }