RSS Feed Subscribe to RSS Feed


Persisting Money class with Hibernate

Further to my previous post about representing monetary amounts in Java, I have been using the TimeAndMoney library.

I ran into some problems persisting my classes that use Money via Hibernate. I should point out that these are not problems with the Money class or the timeandmoney library, rather than with my hibernate setup, but I thought I would post my approach here for future reference.

I started by incorrectly trying to map my Money field (in my case, called ‘openingBalance) as a property, viz:

<property name=”openingBalance” type=””>

Which resulted in the following error:

SEVERE: Data truncation: Data too long for column ‘openingBalance’ at row 1
Exception in thread “main” org.hibernate.exception.GenericJDBCException: could not insert…

Then I tried mapping it as a component, viz

<component name=”openingBalance” class=””>

<property name=”amount”/>

<property name=”currency”/>


But this resulted in the following error:

Initial SessionFactory creation Could not find a setter for property amount in class
Exception in thread “main” java.lang.ExceptionInInitializerError

This is because the Money class has no setAmount or setCurrency methods. The solution is to specify field access (as opposed to accessor method access), as in

<component name=”openingBalance” class=””>

<property access=”field” name=”amount”/>

<property access=”field” name=”currency”/>


Note that if you check the Money javadocs, it (correctly) says that the setters are not provided because they would break encapsulation They do however (and I quote, “begrudgingly”) provide alternative setters such as setForPersistentMapping_Amount, but I am not sure how to get Hibernate to use these, and in this case, I don’t think it is necessary or beneficial anyway.

Tags: , ,

2 Responses to “Persisting Money class with Hibernate”

  1. Guy |

    … and as what sql data type is the money saved in the database? doesn’t it suffer from all the rounding errors and limited capacity? as described here:

  2. sabram |

    Hi Guy,
    I no longer use timeandmoney. It seems to be a dead project. I think it is sad, incredible even, that Java still doesn’t have a good way of managing money.

    I think the post you linked to has the right idea of either using long, or long wrapped in a custom Money class. Thanks for the link to the post…


Leave a Reply