As many people, I don't like having my "business" objects making reference to Hibernate stuff. This applies to my enums as well (moreover I wanted to persit them as char instead of the default int).
So, as suggested by Gavin, I wrote a set of UserType for these objects. Now the Hibernate specific code is cleanly separated and kept in separated packages. Cool.
Unfortunately, I had some difficulties to use these objects (mapping using custom types) with the Query API.
Lets consider the following example:
- Business object/type:
StatusEnum
- Corresponding user type:
StatusEnumType
The
Invoice business object has a property of type
StatusEnum.
I want to query for all invoices having a given status, so I write the following query:
Code:
Query q = s.createQuery("from Invoice where status=:status");
q.setParameter("status", StatusEnum.OPENED);
return q.list();
This code doesn't work properly because Hibernate doesn't (apparently) detect it should use the custom StatusEnumType user type to translate the parameter into its DB representation.
The workaround was to write the query as follows:
Code:
Query q = s.createQuery("from Invoice where status=:status");
q.setParameter("status", StatusEnum.OPENED, Hibernate.custom(StatusEnumType.class));
return q.list();
I'm wondering if Hibernate could detect this situation itself, and use the appropriate user type when needed - just as it detects persistent entities from other kinds of objects. It is so easier to write the query in its first form, and less error prone (the developper doesn't have to be aware of the actual type used to persist the thing).
Feedback ?