如何使用hibernate util优化dao?

时间:2016-03-29 07:17:57

标签: java hibernate

我只想删除重复代码,比如事务初始化和try catch块,并把它放在我的Hibernate util类中。

这是我的PersonDao课程

public class PersonDao {

    public List<Person> getAllPersons(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        List<Person> persons = new ArrayList<>();
        try{
            tx = session.beginTransaction();
            Criteria cr = null;
                cr = session.createCriteria(Person.class);
                persons = cr.list();
        }catch (RuntimeException e) {
            e.printStackTrace();
        }finally {
            session.close();
        }
        return persons;
    }

    public Person getPersonById(int id) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        Person person = null;
        try{
            tx = session.beginTransaction();
            String hql = "from Person where id = :id";
            Query query = session.createQuery(hql);
            query.setParameter("id",id);
            person = (Person) query.uniqueResult();
        }catch(RuntimeException e){
            e.printStackTrace();
        }finally{
            session.close();
        }
        return person;
    }

    public List<Person> getPersonByRole(String role){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        List<Person> persons = new ArrayList<>();
        try{
            tx = session.beginTransaction();
            String hql = "from Person where role = :role";
            Query query = session.createQuery(hql);
            query.setParameter("role",role);
            persons = query.list();
        }catch(RuntimeException e){
            e.printStackTrace();
        }finally{
            session.close();
        }
        return persons; 
    }

    public void addPerson(Person person){
        Transaction transaction = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            transaction = session.beginTransaction();
            session.save(person);
            session.getTransaction().commit();
        }catch(RuntimeException e){
            if(transaction != null){
                transaction.rollback();
            }
            e.printStackTrace();
        }finally{
            session.close();
        }
    }

    public void updatePerson(Person person){
        Transaction transaction = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            transaction = session.beginTransaction();
            session.update(person);
            session.getTransaction().commit();
        }catch(RuntimeException e){
            if(transaction != null){
                transaction.rollback();
            }
            e.printStackTrace();
        }finally{
            session.close();
        }
    }

    public void deletePerson(int id){
        Transaction transaction = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try{
            transaction = session.beginTransaction();
            Person person = (Person)session.get(Person.class, id);
            session.delete(person);
            session.getTransaction().commit();
        }catch(RuntimeException e){
            if(transaction != null){
                transaction.rollback();
            }
            e.printStackTrace();
        }finally{
            session.close();
        }
    }
}

这是我的hibernate util类

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

任何建议如何优化我的dao类。感谢

2 个答案:

答案 0 :(得分:0)

如果您想开发自己的自定义实现,可以使用this pattern

  public static <T> T doInTransaction(IRequest<T> request) {
        Transaction txn = null;
        Session session = openSession();

        T result = null;

        try {
            txn = session.beginTransaction();
            result = request.doInTransaction(session);
            txn.commit();
        } catch (Throwable th) {
            InternalUtils.HibernateUtils.rollback(txn);
            throw InternalUtils.toRuntimeException(th);
        } finally {
            InternalUtils.HibernateUtils.close(session);
        }

        return result;
    }

use

的示例
public List<T> list() {
    return HibernateSessionFactory.doInTransaction(new IRequest<List<T>>() {
        @Override
        public List<T> doInTransaction(Session session) {
            return tuneCriteriaForList(createCriteria(session)).list();
        }
    });
}

您可以更进一步,使用getCurrentSession()和只读事务进行读取请求。

但最好的方法是使用Spring Framework。

答案 1 :(得分:0)

确实在 HibernateUtil.class 中构建会话不是一个正确的操作,但是如果您想摆脱重复代码来构建会话,您可以将您的 PersonDao.class 更改为:

public class PersonDao {

Session session= HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

public List<Person> getAllPersons(){
    List<Person> persons = new ArrayList<>();
    try{
        Criteria cr = session.createCriteria(Person.class);
        persons = cr.list();
    }catch (RuntimeException e) {
        e.printStackTrace();
    }finally {
        session.close();
    }
    return persons;
}

public Person getPersonById(int id) {
    Person person = null;
    try{
        String hql = "from Person where id = :id";
        Query query = session.createQuery(hql);
        query.setParameter("id",id);
        person = (Person) query.uniqueResult();
    }catch(RuntimeException e){
        e.printStackTrace();
    }finally{
        session.close();
    }
    return person;
}

public List<Person> getPersonByRole(String role){
    List<Person> persons = new ArrayList<>();
    try{
        String hql = "from Person where role = :role";
        Query query = session.createQuery(hql);
        query.setParameter("role",role);
        persons = query.list();
    }catch(RuntimeException e){
        e.printStackTrace();
    }finally{
        session.close();
    }
    return persons;
}

public void addPerson(Person person){
    try{
        session.save(person);
        session.getTransaction().commit();
    }catch(RuntimeException e){
        if(tx != null){
            tx.rollback();
        }
        e.printStackTrace();
    }finally{
        session.close();
    }
}

public void updatePerson(Person person){
    try{
        session.update(person);
        session.getTransaction().commit();
    }catch(RuntimeException e){
        if(tx != null){
            tx.rollback();
        }
        e.printStackTrace();
    }finally{
        session.close();
    }
}

public void deletePerson(int id){
    try{
        Person person = (Person)session.get(Person.class, id);
        session.delete(person);
        session.getTransaction().commit();
    }catch(RuntimeException e){
        if(tx != null){
            tx.rollback();
        }
        e.printStackTrace();
    }finally{
        session.close();
    }
}
}