For one of my projects, I have used Java 5 Generics to simplify creation of Hibernate DAO’s. I no longer have to duplicate the typical CRUD operations in every DAO class. Note that I am using HibernateDaoSupport. If you want to see an example of a non-Spring generic DAO, the authors of Hibernate have posted one on their blog. Though mine may not be the best practices for Hibernate, I thought I’d post it just to show an example of what can be done with Java 5 generics and how much code can be reduced with it.
Here is my generic class:
I have a generic interface to go along with this class:
And now for an example usage with a Hibernate domain object of type PageCache which has an Integer for its primary key. The interface:
And the implementation of that interface:
Note that the getDomainClass() method was just to so I could get the class name for use in my Hibernate queries. There does not appear to be a way to get it from the generic class type. Maybe there is another way to do it, or maybe I could have constructed Hibernate queries differently to work around it.
My open-sourced projects (currently inactive) that use this: