Thursday, July 26, 2012

Generic typesafe DAO with Guice and Hibernate

DAOs are an important part of many applications in the Java world. Most if not all entity classes will need a DAO for basic operations such as retrieval, persistence, updating and deletion. Writing a DAO for each and every entity can be a daunting task, not to mention that those operations will be duplicated among other DAOs.

Fortunately, there is an easy way to deal with this problem. It's possible to create a single DAO implementation which can be used to operate on any entity class. It is accomplished using Java Generics and Guice's TypeLiteral. For backwards compatibility with previous platforms, generic type information is erased during compilation, and therefore there's no way to determine the generic class at run-time. TypeLiteral tries to workaround this limitation allowing the generic type to be retained and queried at run-time. Basically, it works as a wrapper, and thus DAO bindings will look a bit different.