Monday, May 3, 2010

Dynamic DAO generation

Almost any developer working on enterprise projects spend reasonable amount of time writing DAO classes and tests for them.
Most of this code is trivial, especially in case of ORM frameworks, and I think that it should be generated instead of hand-writing. Why should I waste my time writing routine code, writing tests for it and leaving space for errors despite of tests?
So I wrote very small framework (not actually framework, just a few classes) that generates DAO classes for Hibernate framework.
You just write interfaces for DAO, annotate them and framework do all the routine work for you.
Code being generated is usually as effective as hand-written one and [most] of bugs are already fixed.

Here how DAO interface looks:
public interface EntityDao extends DynamicDao<Entity, Long> {
        List<SomeEntity> getPaginatedFilteredByCriteriaOrderedByCriteria(
            @Pagination.Paginate Pagination pagination,
            @Restriction.Restrict Restriction restriction,
            @Ordering.Criteria Ordering ordering

Here how it can be used:
EntityDao entityDao = (EntityDao) DaoFactory.getInstance(EntityDao.class, Entity.class, sessionFactory);
List<Entity> entities = entityDao.getPaginatedFilteredByCriteriaOrderedByCriteria(
    new Pagination(6, 7), 
        Restriction.ilike("name", "vaLue 1"),"name", "value 2")),
    new Ordering("name", Ordering.Direction.DESC).Order("id"));

And this is example of actual code auto-generated for interface method above:
public List getPaginatedFilteredByCriteriaOrderedByCriteria(
   Pagination p0, Restriction p1, Ordering p2) {
    Session session = ThreadLocalSessionFactory.getSession();
    Criteria criteria = session.createCriteria(entityClass);
    Restriction restrictionValue = p1;
    Criterion criterion = getCriterion(restrictionValue);
    if (criterion != null) {
    Ordering sortingCriteriaValue = p2;
    while (sortingCriteriaValue != null) {
        if (sortingCriteriaValue.getDirection() == Ordering.Direction.ASC) {
        } else if (sortingCriteriaValue.getDirection() == Ordering.Direction.DESC) {
        sortingCriteriaValue = sortingCriteriaValue.getChild();
    if (p0 != null) {
    return criteria.list();

Generated DAO classes can be easily exposed as Spring beans.

More information, docs and examples on project's site on Google Code:

The framework is not finished yet (code is not well documented, there are possibly bugs left etc.) and I have no time for it right now but I hope it will look as a real project in near future.
It looking stable and I know at least one project in production stage that is using it.
Anyone interested in project development are welcome.