BaseDao+万能方法 , HibernateDaoSupport

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.sun.crypto.provider.RC2Cipher;

/**
 * 
 * @author Administrator
 * 数据访层基类
 *
 */
public class BaseDao {
	
	/*
	 *打开数据库连接
	 */
	public Connection getConn(){
		
		Connection conn = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	
	/*
	 * 关闭的方法
	 * 释放资源
	 * 后开的先关
	 */
	public void closeAll(Connection conn,PreparedStatement pstmt,ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		if(pstmt!=null){
			try {
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
		
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
	
	
	/*
	 * 万能方法
	 * 只能增、删除、改。
	 * 不能查
	 */
	public int executeSql(String sql,Object[] param){
		 Connection conn = null;//数据库连接
		 PreparedStatement pstmt = null;
		 int num = 0;
		
		 try {
		    conn = this.getConn();//得到数据库连接
			pstmt = conn.prepareStatement(sql);
			
			if(param!=null){
				
				for (int i = 0; i < param.length; i++) {
					 pstmt.setObject(i+1, param[i]);
				}
				
			}
			 num =  pstmt.executeUpdate();//增、删除、改全用这个方法
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.closeAll(conn, pstmt,null);
		}
		
		return num;
		
	}
	
}

  

 

BaseHibernateDAO

 

 

package dao.impl;



import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
/**
 * 
 * 操作数据库底层类
 *
 */
public abstract class BaseHibernateDAO {
	private Session session;
	private boolean isClose = false;//是否是调用者关闭Session
	/**
	 * 
	 * @param cla
	 * @param id
	 * @return
	 */
	protected Object getObject(Class cla,java.io.Serializable id){
		Object object = null;
		session = this.getSession();
		try{
			object = session.get(cla, id);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			if(!isClose){
			this.closeSession();
			}
		}	
		return object;
	}
	
	/**
	 * 
	 * @param cla
	 * @param id
	 * @return
	 */
	protected Object loadObject(Class cla,java.io.Serializable id){
		Object object = null;
		session = this.getSession();
		try{
			object = session.load(cla, id);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			if(!isClose){
			this.closeSession();
			}
		}	
		return object;
	}
	
	/**
	 * 添加数据
	 */
	protected boolean add(Object object){
		Transaction tx = null;
		session = this.getSession();
		try{
			tx = session.beginTransaction();//开启事务
			session.save(object);
			tx.commit();//提交事务
		}catch(Exception ex){
			if(tx!=null)tx.rollback();//回滚
			ex.printStackTrace();
			return false;
		}finally{
			if(!isClose)
			this.closeSession();
		}
		return true;
	}
	/**
	 * 修改数据
	 */
	protected boolean update(Object object){
		Transaction tx = null;
		session = this.getSession();
		try{
			tx = session.beginTransaction();//开启事务
			session.update(object);
			tx.commit();//提交事务
		}catch(Exception ex){
			if(tx!=null)tx.rollback();//回滚
			ex.printStackTrace();
			return false;
		}finally{
			if(!isClose)
			this.closeSession();
		}
		return true;
	}
	/**
	 * 删除数据
	 */
	protected boolean delete(Class cls,java.io.Serializable id){
		Transaction tx = null;
		Object object = this.getObject(cls, id);
		session = this.getSession();
		try{
			tx = session.beginTransaction();//开启事务
			session.delete(object);//获得对象并作删除
			tx.commit();//提交事务
		}catch(Exception ex){
			if(tx!=null)tx.rollback();//回滚
			ex.printStackTrace();
			return false;
		}finally{
			if(!isClose)
			this.closeSession();
		}
		return true;
	}
	/**
	 * 删除数据
	 */
	protected boolean deleteAll(String sql){
		Transaction tx = null;
		session = this.getSession();
		try{
			tx = session.beginTransaction();//开启事务
			Query query = session.createQuery(sql.toString());
			
			int i = query.executeUpdate();
			System.out.println("======="+i);
//获得对象并作删除
			tx.commit();//提交事务
		}catch(Exception ex){
			if(tx!=null)tx.rollback();//回滚
			ex.printStackTrace();
			return false;
		}finally{
			if(!isClose)
			this.closeSession();
		}
		return true;
	}
	
	/**
	 *  根据条件进行高级查询
	 */
	protected List search(Class clazz,Object condition){
		List list = null;
		try {
			List results = this.getSession().createCriteria(clazz).add(Example.create(condition)).list(); 
		    return results;
		} catch (Exception e) {
			return list;
		}finally{
			if(!isClose)
				this.closeSession();
		}
	}
	
	/**
	 * 根据SQL查询
	 */
	protected List selectBySql(String sql){
		List list = null;
		try{
			list = this.getSession().createSQLQuery(sql).list();
			return list;
		}catch(Exception ex){			
			ex.printStackTrace();
			return list;
		}finally{
			if(!isClose)
			this.closeSession();			
		}
	}
	
	/**
	 * 根据HQL查询
	 */
	protected List selectByHql(String Hql){
		List list = null;
		session = this.getSession();
		try{
			list = session.createQuery(Hql).list();
			return list;
		}catch(Exception ex){			
			ex.printStackTrace();
			return list;
		}finally{
			if(!isClose)
			this.closeSession();			
		}
	}


	
	/**
	 * 
	 * @return
	 */
	protected Session getSession() {
	
		if(this.session==null){
			this.session = HibernateSessionFactory.getSession();
			System.out.println("-----开启Session-----");
		}
		return this.session;
	}
	public void setSession(Session session) {
		this.session = session;
	}
	
	public void closeSession(){
		
		this.session = null;
		HibernateSessionFactory.closeSession();
		System.out.println("-----关闭Session-----");
		
	}
	public void setClose(boolean isClose) {
		this.isClose = isClose;
	}

}

  

CommonDao

package com.hljzr.framework.dao;


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

public interface CommonDao {

    /**
     * 查询列表(不分页)
     *
     * @param hql语句
     * @return list
     */
    public List query(String hql);


    /**
     * 查询一条
     *
     * @param cla Class类
     * @param id  主键
     * @return
     */
    public Object queryById(Class cla, Serializable id);

    /**
     * 保存一条数据
     *
     * @param obj 对象
     * @return
     */
    public void save(Object obj);

    /**
     * 保存一条数据
     *
     * @param obj 对象
     * @return
     */
    public void save(Collection c);

    /**
     * 修改一条数据
     *
     * @param obj 对象
     * @return
     */
    public void update(Object obj);

    /**
     * 删除一条数据
     *
     * @param obj 对象
     * @return
     */
    public void delete(Object obj);

    /**
     * 删除多条数据
     *
     * @param obj 对象
     * @return
     */
    public void delete(Collection c);


    /**
     * 清空session中的特定实体
     */
    public void clear(Object obj);


    /***
     * 分页查询
     *
     * @param offset
     *            当前页数
     * @param pageSize
     *            每页显示的条数
     * @return 返回要查询的集合
     */
    public List findByPage(final String hql,
                           final int offset, final int pageSize);


    /**
     * 获取总条数
     */
    public Long getTotalCount(String hql);


    /**
     * 获取要分的页数
     *
     * @param pageSize 每页显示的条数
     */

    public Long getTotalPages(String hql, Integer pageSize);
	

    /**
     * 单个参数分页查询
     *
     * @param hql
     * @param value
     * @param offset
     * @param pageSize
     * @return
     */
    public List findByPage(final String hql, final Object value,
                           final int offset, final int pageSize);

    /**
     * 多个参数分页查询
     *
     * @param hql
     * @param values
     * @param offset
     * @param pageSize
     * @return
     */
    public List findByPage(final String hql, final Object[] values,
                           final int offset, final int pageSize);
}

  

CommonDaoImpl
package com.hljzr.framework.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hljzr.framework.dao.CommonDao;

public class CommonDaoImpl extends HibernateDaoSupport implements CommonDao {

    public List query(String hql) {

        return super.getHibernateTemplate().find(hql);
    }

    public Object queryById(Class cla, Serializable id) {

        return this.getHibernateTemplate().get(cla, id);
    }

    public void save(Object obj) {
        super.getHibernateTemplate().save(obj);
    }

    public void update(Object obj) {
        super.getHibernateTemplate().update(obj);
    }

    public void delete(Object obj) {
        super.getHibernateTemplate().delete(obj);
    }

    public void delete(Collection c) {
        super.getHibernateTemplate().deleteAll(c);
    }

    public void save(Collection c) {
        super.getHibernateTemplate().saveOrUpdateAll(c);
    }

    public void clear(Object obj) {
        super.getHibernateTemplate().evict(obj);

    }

    /***
     * 分页查询
     *
     * @param pageNo
     *            当前页数
     * @param pageSize
     *            每页显示的条数
     * @return 返回要查询的集合
     */
    public List findByPage(final String hql, final int pageNo,
                           final int pageSize) {
        List list = getHibernateTemplate().executeFind(new HibernateCallback()// 回调函数
        {
            // 实现HibernateCallback接口必须实现的方法
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                // 执行Hibernate分页查询

                List result = session.createQuery(hql).setFirstResult(
                        (pageNo - 1) * pageSize)// 索引值从“0”开始
                        .setMaxResults(pageSize)// 要显示几条
                        .list();
                return result;
            }
        });
        return list;
    }


    /**
     * 获取总条数
     */
    public Long getTotalCount(String hql) {
        return (Long) super.getHibernateTemplate().find(hql).get(0);
    }


    /**
     * 获取要分的页数
     */

    public Long getTotalPages(String hql, Integer pageSize) {
        Long totalpages;

        Long all = this.getTotalCount(hql);

        totalpages = (all % pageSize == 0) ? (all / pageSize)
                : (all / pageSize + 1);
        return totalpages;
    }


    /**
     * 带参数分页查询 (单个参数)
     */
    public List findByPage(final String hql, final Object value,
                           final int offset, final int pageSize) {
        // 通过一个HibernateCallback对象来执行查询
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {
            // 实现HibernateCallback接口必须实现的方法
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                // 执行Hibernate分页查询
                List result = session.createQuery(hql)
                        // 为hql语句传入参数
                        .setParameter(0, value).setFirstResult(offset)
                        .setMaxResults(pageSize).list();
                return result;
            }
        });
        return list;
    }


    /**
     * 多个参数分页查询
     */
    public List findByPage(final String hql, final Object[] values,
                           final int offset, final int pageSize) {
        // 通过一个HibernateCallback对象来执行查询
        List list = getHibernateTemplate().executeFind(new HibernateCallback() {
            // 实现HibernateCallback接口必须实现的方法
            public Object doInHibernate(Session session)
                    throws HibernateException, SQLException {
                // 执行Hibernate分页查询
                Query query = session.createQuery(hql);

                // 为hql语句传入参数
                for (int i = 0; i < values.length; i++) {
                    query.setParameter(i, values[i]);
                }
                List result = query.setFirstResult(offset).setMaxResults(
                        pageSize).list();
                return result;
            }
        });
        return list;
    }
}

  

posted @ 2019-10-19 22:33  幸福流浪  阅读(518)  评论(0编辑  收藏  举报