Issue
I am using hibernate to persist my data. It's a financial application and I am having a hard time persisting the most fundamental entity of the application which is 'Money'. I was using JodaMoney but it's immutable so I am not able to find a good way to persist it. And without persisting my money to database, there is no point of making the application. What would I do with the immutability when I can't even store the state of my object? Then I started creating my own 'Money'(fields as BigDecimal amount and java.util.Currency for currency), I wanted to use 'Currency' of java.util . But, that doesn't have a public constructor so hibernate can not persist that. Please guide me on how to deal with this?
EDIT1: The code for most basic class:
@Entity
public class BasicMoney {
@Embedded
@Id
private BigDecimal amount;
@Embedded
private Currency currency;
//getters and setters, other methods
}
Now, when I make an object of this class and try to store it into database, it doesn't work. Hibernate throws:
org.hibernate.InstantiationException: No default constructor for entity: : java.util.Currency
So, this is the problem which I am facing.
Solution
You could use a workaround
@Embedded
String currency; //store data as a string
public void setCurrency(Currency currency) {
this.currency = currency.getCurrencyCode(); //conversion to an actual currency
}
public Currency getCurrency() {
return Currency.getInstance(currency); //conversion to an actual currency
}
Answered By - Evgeniy Dorofeev