3

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?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
janlan
  • 477
  • 1
  • 5
  • 19

2 Answers2

5

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) {...}
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
0

You cannot map MonetaryAmount directly.

You can try mapping it to BigDecimal, then in your code perform a conversion, or you can try implementing a Hibernate custom type (try searching for @Type, or using JPA conversion (if JPA is 2.1 or above). This answer has some nice links on the subject.

Vitor Santos
  • 581
  • 4
  • 15