Hibernate: CRUD Generic DAO

Fabio B. picture Fabio B. · Mar 15, 2012 · Viewed 57.6k times · Source

My web application has got a lot of service tables/entities, such as payment_methods, tax_codes, province_codes, etc.

Each time I add a new entity, I have to write a DAO. The thing is that, basically, they are all the same, but the only difference is the entity class itself.

I know that Hibernate tools can generate the code for me automatically but I can't use them now (don't ask why) so I'm thinking of a Generic DAO. There's a lot of literature about that but I can't put pieces together and make it work with Spring.

It's all about generics I think, it will have four basic methods:

  • listAll
  • saveOrUpdate
  • deleteById
  • getById

and that's all.


Question:

What's the best practice for not re-inventing the wheel? Isn't there something ready to use, yet?

Answer

NimChimpsky picture NimChimpsky · Mar 15, 2012

here's mine

@Component
public class Dao{

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

    public <T> T save(final T o){
      return (T) sessionFactory.getCurrentSession().save(o);
    }


    public void delete(final Object object){
      sessionFactory.getCurrentSession().delete(object);
    }

    /***/
    public <T> T get(final Class<T> type, final Long id){
      return (T) sessionFactory.getCurrentSession().get(type, id);
    }

    /***/
    public <T> T merge(final T o)   {
      return (T) sessionFactory.getCurrentSession().merge(o);
    }

    /***/
    public <T> void saveOrUpdate(final T o){
      sessionFactory.getCurrentSession().saveOrUpdate(o);
    }

    public <T> List<T> getAll(final Class<T> type) {
      final Session session = sessionFactory.getCurrentSession();
      final Criteria crit = session.createCriteria(type);
  return crit.list();
    }
// and so on, you shoudl get the idea

and you can then access like so in service layer:

 @Autowired
    private Dao dao;

   @Transactional(readOnly = true)
    public List<MyEntity> getAll() {
      return dao.getAll(MyEntity.class);
    }