Hibernate实现BaseDao

设计思路

  • BaseDao为各个实体Dao类的接口,定义了各个增删改查方法。
  • BaseDaoImpl实现BaseDao,子类可继承该类,获取dao层的基本方法。
  • UserDao为一个具体的实体的dao接口,该接口继承BaseDao,并可以再继续写入新的 方法。
  • UserDaoImpl为UserDao的实现类,该类继承BaseDaoImpl,实现UserDao。
  • UserDaoTest为测试类

类图如下:
Hibernate实现BaseDao_第1张图片

实现代码


    • BaseDao实现代码:
package dao;

import java.io.Serializable;
import java.util.List;

/**
 * dao层基类,实现增删改查
 * @author PC-ASUS(zzs)
 *
 * @param 
 */
public interface BaseDao {

    //添加一个对象
    void save(T entity);
    //更新一个对象,所有属性
    void update(T entity);
    //更新一个对象,部分属性
    void partUpdate(int id, String[] names, Object[] values);
    //删除一个对象
    void delete(Serializable id);
    //根据id查找一个对象
    T findById(Serializable id);
    //根据HQL返回对象List
    List findByHQL(String hql, Object... params);
    //分页查询
    List queryPage(String hql, int pageNo, int pageSize);
}
  • BaseDaoImpl实现代码:

package dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import utils.HibernateSessionFactory;
import dao.BaseDao;

public class BaseDaoImpl implements BaseDao{

    private Class clazz; //T的具体类

    /**
     * 通过构造方法指定DAO的具体实现类
     */
    @SuppressWarnings("unchecked")
    public BaseDaoImpl() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class) type.getActualTypeArguments()[0];
        //System.out.println("DAO的真实实现类是:"+this.clazz.getName());
    }

    /**
     * 获取当前工作的Session
     */
    protected Session getSession(){
        return HibernateSessionFactory.getSession();
    }


    @Override
    public void save(Object entity) {
        Session session = null;
        Transaction tx = null;
        try{
            session = this.getSession();
            tx = session.beginTransaction();
            session.save(entity);
            tx.commit();
        }catch(Exception ex){
            System.out.println("保存对象出现错误!");
            ex.printStackTrace();
            if(tx != null){
                tx.rollback();
            }
        }finally{
            if(session != null){
                session.close();
            }
        }
    }

    @Override
    public void update(Object entity) {
        Session session = null;
        Transaction tx = null;
        try{
            session = this.getSession();
            tx = session.beginTransaction();
            session.update(entity);
            tx.commit();
        }catch(Exception ex){
            System.out.println("更新对象出现错误!");
            ex.printStackTrace();
            if(tx != null){
                tx.rollback();
            }
        }finally{
            if(session != null){
                session.close();
            }
        }
    }

    @Override
    public void partUpdate(int id, String[] names, Object... values) {
        Session session = null;
        Transaction tx = null;
        try{
            session = this.getSession();
            tx = session.beginTransaction();

            String tab = clazz.getSimpleName();
            String hql = "update "+tab+" t";
            for(int i = 0;i < names.length;i ++){
                hql += " set t."+names[i]+"=?";
            }
            hql += " where t.id="+id;
            Query query = session.createQuery(hql);
            for(int i = 0;i < values.length;i ++){
                query.setParameter(i, values[i]);
            }
            System.out.println("部分更新:"+hql);
            query.executeUpdate();
            tx.commit();
        }catch(Exception ex){
            System.out.println("更新对象部分属性出现错误!");
            ex.printStackTrace();
            if(tx != null){
                tx.rollback();
            }
        }finally{
            if(session != null){
                session.close();
            }
        }
    }

    @Override
    public void delete(Serializable id) {

        T obj = findById(id);

        Session session = null;
        Transaction tx = null;
        try{
            session = this.getSession();
            tx = session.beginTransaction();
            session.delete(obj);
            tx.commit();
        }catch(Exception ex){
            System.out.println("删除对象出现错误!");
            ex.printStackTrace();
            if(tx != null){
                tx.rollback();
            }
        }finally{
            if(session != null){
                session.close();
            }
        }
    }

    @Override
    public T findById(Serializable id) {
        Session session = null;
        Transaction tx = null;
        T obj = null;
        try{
            session = this.getSession();
            tx = session.beginTransaction();

            obj = (T) session.get(clazz, id);

            tx.commit();
        }catch(Exception ex){
            System.out.println("查找对象出现错误!");
            ex.printStackTrace();
            if(tx != null){
                tx.rollback();
            }
        }finally{
            if(session != null){
                session.close();
            }
        }
        return obj;
    }

    @Override
    public List findByHQL(String hql, Object... params) {
        List list = null;
        Session session = null;
        Transaction tx = null;
        try{
            session = this.getSession();
            tx = session.beginTransaction();

            Query query = session.createQuery(hql);
            for(int i = 0;params != null && i < params.length; i ++){
                query.setParameter(i, params[i]);
            }
            System.out.println("HQL查询:"+hql);
            list = query.list();

            tx.commit();
        }catch(Exception ex){
            System.out.println("执行HQL查找对象出现错误!");
            ex.printStackTrace();
            if(tx != null){
                tx.rollback();
            }
        }finally{
            if(session != null){
                session.close();
            }
        }
        return list;
    }

    @SuppressWarnings("unchecked")
    public List queryPage(String hql, int pageNo, int pageSize){
        List list = null;
        Session session = null;
        Transaction tx = null;
        try{
            session = this.getSession();
            tx = session.beginTransaction();

            Query query = session.createQuery(hql);
            list = query.setFirstResult((pageNo - 1) * pageSize)
                        .setMaxResults(pageSize)
                        .list();

            tx.commit();
        }catch(Exception ex){
            System.out.println("分页查询出现错误出现错误!");
            ex.printStackTrace();
            if(tx != null){
                tx.rollback();
            }
        }finally{
            if(session != null){
                session.close();
            }
        }
        return list;
    }

}
  • UserDao实现代码
package dao;

import model.User;

public interface UserDao extends BaseDao<User>{

}
  • UserDaoImpl实现代码
package dao.impl;

import model.User;
import dao.UserDao;

public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao{
}

测试:

package dao.impl;

import java.util.List;

import org.junit.Test;

import model.User;
import dao.UserDao;

public class UserDao_Test {
    //@Test
    public void saveTest(){
        User user = new User();
        user.setName("aaa");
        user.setPassword("123456");
        UserDao userDao = new UserDaoImpl();
        userDao.save(user);
    }

    //@Test
    public void deleteTest(){
        UserDao userDao = new UserDaoImpl();
        userDao.delete(2);
    }

    //@Test
    public void findByIdTest(){
        UserDao userDao = new UserDaoImpl();
        User user = userDao.findById(2);
        System.out.println(user.getName());
    }

    //@Test
    public void updateTest(){
        UserDao userDao = new UserDaoImpl();
        User user = new User();
        user.setId(1);
        user.setName("yyy");
        userDao.update(user);
    }

    //@Test
    public void partUpdateTest(){
        int id = 1;
        String[] names = {"password"};
        Object[] values = new Object[names.length];
        values[0] = "4645654";
        UserDao userDao = new UserDaoImpl();
        userDao.partUpdate(id, names, values);
    }

    //@Test
    public void findByHQLTest(){
        //String hql = "update User t set t.password=? where t.id=1";
        String hql = "from User u where u.id = ?";
        Object[] params = {1};
        UserDao userDao = new UserDaoImpl();
        User user = userDao.findByHQL(hql, params).get(0);
        System.out.println(user.toString());
    }


    @Test
    public void queryPageTest(){
        //插入数据
        /*for(int i = 1;i <= 40;i ++){
            this.saveTest();
        }*/
        String hql = "from User u";
        UserDao userDao = new UserDaoImpl();
        List users = userDao.queryPage(hql, 2, 3);
        for(User user : users){
            System.out.println(user);
        }
    }
}

重点描述

  • 利用反射机制,获取具体实现类
ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[0];
        //System.out.println("DAO的真实实现类是:"+this.clazz.getName());
  • 对应Hibernate中Session提供的update方法,或对实体的所有属性进行更新,可能导致某些值变为null。当我们只想更新对象部分属性时,可以通过执行hql语句解决这个问题。

你可能感兴趣的:(Hibernate)