简体   繁体   中英

creating a generic DAO class for Hibernate

In my web application, there are quite a few entities, and most of them require CRUD operations. So I am thinking about writing a generic DAO that can handle CRUD for all of the entities. I've found a tutorial article from IBM, but don't quite understand the generic implementation using the generic type 'T', and 'PK'. The article is at this link

I wrote the following DAO by using Object type in all the methods, and they seem working just fine - all my entities are able to do CRUD with the following CommonDao class. Although it works for my needs, I'm looking for what is the best practice for implementing a generic DAO class for Hibernate.

public class CommonDao
{
    private final static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public CommonDao() {}

    @UnitOfWork
    public List findAll(Object className)
    {
        List types = null;

        Session session = sessionFactory.openSession();
        Criteria criteria = session.createCriteria(className + ".class");
        types = (List <Object>) criteria.list();
        session.close();

        return types;
    }

    @Transactional
    public void saveObject(Object obj)
    {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.saveOrUpdate(obj);

        tx.commit();
        session.close();
    }

    @Transactional
    public void saveObjectWithManyEntities(Object obj, Set<Object> objects)   /* for OneToMany relationships */
    {
        Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        session.saveOrUpdate(obj);

        for (Object o : objects)
        {
            session.save(o);
        }

        tx.commit();
        session.close();
    }
}

The best way to do it is to include Spring Data into your project. The JPA repositories offer basic CRUD, pagination, sorting and most of your queries could be built automatically from the methods naming convention.

Before Spring Data we'd resort to such Generic Daos but not anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM