Reputation: 7236
In the book Java Persistence with Hibernate
, it discusses the following use case for using a UserType
:
We need to store monetary amount in DB, but users can use any currency for it. So we 'normalize' the amount to USD before storing it in DB, and use a UserType
implementation that will convert the amount to USD before storing, and to a user specified currency after reading it from DB but before giving it back to a user.
I can think of two other approaches to do this:
1) use field access for Hibernate for storing/reading from DB, and use public getter/setter for the conversion,
2) create a pair of private getter/setter for Hibernate which will use USD, and a public getter/setter for the necessary conversion for a user.
How do these approaches compare with using UserType
? Are there any other advantages to UserType
?
Upvotes: 0
Views: 1471
Reputation: 14061
Book examples are usually poor. Not that the book itself is poor. I, for instance, think that Java Persistence with Hibernate is the best Hibernate book out there. But the examples have to be concise and self-contained, so, a bit far from the real world.
If I remember correctly, this example serves only to demonstrate how to use a UserType, and it shows a lot of the features for it (specially the "reading back" part). The use-case itself is not important. So, I'd totally abstract the use case they presented.
For this particular scenario, if you ever need to store currencies in your database, I'd recommend taking a look at Joda Money. They provide some ready-to-use JPA user types, so you don't need to worry about it. And yes, doing real-time conversion between currencies is not something you want to keep in your JPA entity. I'd have an EJB service to do that.
Upvotes: 1
Reputation: 1459
As a general rule of thumb I would say that UserType
is appropriate for rather technical concerns while code in your model should focus on the domain concerns.
Imo User Types in Hibernate shows some good examples for technical conversion concerns like int-to-Date and so on which are well placed inside a UserType
.
Concerning the currency example you gave I would say it strongly depends on the concrete scenario if a UserType
is approriate. Currency conversion issues might become very complex and I would rather think these are domain concerns and so place according code in the model and not bury it in a UserType
.
Possible drawback of the UserType
in above example:
Possible advantage:
Upvotes: 2