欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hibernateDAOimpl

程序员文章站 2022-07-02 17:02:37
...

/*******************************************************************************
  ******************************************************************************/

import java.util.List;
import java.util.Iterator;
import java.sql.Connection;
import javax.sql.DataSource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.insigma.common.util.InsigmaException;
import com.opensource.log.NewLogger;

import java.sql.SQLException;
import java.sql.Statement;

public class HibernateDaoImpl extends HibernateDaoSupport implements
  HibernateBaseDao {
 /** 注入的数据源 **/
 protected DataSource dataSource;

 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }

 public DataSource getDataSource() {
  return this.dataSource;
 }

 public HibernateDaoImpl() {
 }

 /**
  * 存储对象
  */
 public void save(Object obj) throws InsigmaException {
  save(new Object[] { obj });
 }

 /**
  * 存储对象数组
  */
 public void save(Object[] obj) throws InsigmaException {
  for (int i = 0; i < obj.length; i++) {
   if (obj[i] == null)
    throw new InsigmaException("存储对象出错,对象为空!\n");
   getHibernateTemplate().save(obj[i]);
  }
  getHibernateTemplate().flush();
 }

 /**
  * 批量存储对象
  */
 public void save(List obj) throws InsigmaException {
  for (int i = 0; i < obj.size(); i++) {
   if (obj.get(i) == null)
    throw new InsigmaException("批量存储对象出错,对象为空!\n");
   getHibernateTemplate().save(obj.get(i));
  }
  getHibernateTemplate().flush();

 }

 /**
  * 批量更新对象
  */
 public void update(List obj) throws InsigmaException {
  for (int i = 0; i < obj.size(); i++) {
   if (obj.get(i) == null)
    throw new InsigmaException("更新对象出错,对象为空!\n");
   getHibernateTemplate().saveOrUpdate(obj.get(i));

  }
  getHibernateTemplate().flush();
 }

 /**
  * 更新对象数组
  */
 public void update(Object[] obj) throws InsigmaException {
  for (int i = 0; i < obj.length; i++) {
   if (obj[i] == null)
    throw new InsigmaException("更新对象出错,对象为空!\n");
   getHibernateTemplate().update(obj[i]);
  }
  getHibernateTemplate().flush();
 }

 /**
  * 更新对象
  */
 public void update(Object obj) throws InsigmaException {
  update(new Object[] { obj });
 }

 /**
  * 执行预处理HQL,如update tab1 set name=?,value=? where id=12
  * 则list的对象为"zhang","qing"
  */
 public void exeHQL(String hql, List list) throws InsigmaException {
  Session ses = getSession();
  try {
   Query query = ses.createQuery(hql);
   Object obj = null;
   for (int i = 0; i < list.size(); i++) {
    obj = list.get(i);
    query.setParameter(i, obj);
   }
   query.executeUpdate();
  } catch (Exception e) {
   NewLogger.getInstance().writeError("执行预处理HQL出错!\n"+e.getMessage(), e);
   throw new InsigmaException(e.getMessage(), e);
  } finally {
   releaseSession(ses);
  }

 }

 /**
  * 执行批量事务,先存储,后更新/删除
  */
 public void exeHQL(Object obj, List list) throws InsigmaException {
  if (obj != null)
   save(obj);
  exeHQL(list);
 }

 /**
  * 先存储对象数据,再执行更新或删除,批量事务执行
  */
 public void exeHQL(Object[] obj, List list) throws InsigmaException {
  if (obj != null)
   save(obj);
  exeHQL(list);
 }

 /**
  * 执行更新或删除HQL语句
  */
 public void exeHQL(String hql) throws InsigmaException {
  Session ses = getSession();
//  try {
   Query query = ses.createQuery(hql);
   query.executeUpdate();
//  } catch (Exception e) {
//   NewLogger.getInstance().writeError("执行更新或删除HQL语句出错!\n"+e.getMessage(), e);
//   throw new InsigmaException(e.getMessage(), e);
//  }
//  finally {
//   releaseSession(ses);
//  }

 }

 /**
  * 执行更新或删除HQL语句
  */
 public void exeHQL(List hql) throws InsigmaException {
  Session ses = getSession();
//  try {
   String sql;
   for (Iterator<String> it = hql.iterator(); it.hasNext();) {
    sql = it.next();
    NewLogger.getInstance().writeDebug(sql);
    Query qr = ses.createQuery(sql);
    qr.executeUpdate();
   }
//  } catch (Exception e) {
//   NewLogger.getInstance().writeError("批量更新或删除出错!"+e.getMessage(), e);
//   throw new InsigmaException(e.getMessage(), e);
//  } finally {
//   releaseSession(ses);
//  }

 }

 /**
  * 查询HQL语句
  */
 public List findObjs(String HQL) throws InsigmaException {
  List list = null;
//  try {
   list = getHibernateTemplate().find(HQL);
//  } catch (DataAccessException e) {
//   NewLogger.getInstance().writeError("查询HQL出错!\n" + e.getMessage(), e);
//   throw new InsigmaException(e.getMessage(), e);
//  }
  return list;

 }

 /**
  * 预编译查询HQL
  */
 public List findObjs(String hql, Object[]prams) throws InsigmaException {
  List reList = null;
//  try {
   reList = getHibernateTemplate().find(hql, prams);
//  } catch (DataAccessException e) {
//   NewLogger.getInstance().writeError("预编译查询HQL出错!\n" + e.getMessage(), e);
//   throw new InsigmaException(e.getMessage(), e);
//  }
  return reList;

 }

 /*
  * 分页查询HQL
  *
  * @
  *
  * @see com.insigma.common.dao.HibernateBaseDao#findObjs(java.lang.String,
  * int, int)
  */
 /**
  * 分页查询HQL
  *
  * @param hql
  *            hql语句
  * @param pageFirst
  *            第几页
  * @param pageRow
  *            每页多少行
  */
 public List findObjs(String hql, int pageFirst, int pageRow)
   throws InsigmaException {
  List list = null;
  Session ses = getSession();
//  try {
   Query qr = ses.createQuery(hql);
   qr.setReadOnly(true);
   qr.setFirstResult((pageFirst - 1) * pageRow);
   qr.setMaxResults(pageRow);
   list = qr.list();
//  } catch (DataAccessException e) {
//   e.printStackTrace();
//   throw new InsigmaException("分页查询出错!\n" + e.getMessage(), e);
//  }
//
//  finally {
//   releaseSession(ses);
//  }
  return list;

 }

 /**
  * 存储并执行HQL
  */
 public void saveObjAndExeHql(List hql, List obj) throws InsigmaException {
  String sql;
  Session ses = getSession();
//  try {
   for (Iterator it = hql.iterator(); it.hasNext();) {
    sql = (String) it.next();
    Query qr = ses.createQuery(sql);
    qr.executeUpdate();
   }
   Object object;
   for (Iterator it = obj.iterator(); it.hasNext();) {
    object = it.next();
    getSession().save(object);
   }
//  } catch (Exception e) {
//   e.printStackTrace();
//   throw new InsigmaException("存储并执行HQL时出错!\n" + e.getMessage(), e);
//  }

//  finally {
//   releaseSession(ses);
//  }

 }

 /**
  * 查询共计记录数
  */
 public int getMaxRow(final String hql) throws InsigmaException {
  int maxRow = (Integer)getHibernateTemplate().execute(new HibernateCallback(){
    public Object doInHibernate(Session session)
      throws HibernateException, SQLException {
     Query qr = getSession().createQuery(hql);
     List list = qr.list();
     int maxRow = 0;
     if (list.size() > 0) {
      String s = String.valueOf(list.get(0));
      if ((s == null) || (s.equals("")))
       s = "0";
      maxRow = Integer.parseInt(s);// ((Integer)
      
     }
     return new Integer(maxRow);
    }
   });
  return maxRow;

 }

 /**
  * 得到数据源连接
  */
 public Connection getConnection() throws InsigmaException {
  Connection con = null;
//  try {
   con = getSession().connection();
//  } catch (Exception e) {
//   e.printStackTrace();
//   throw new InsigmaException("得到数据源连接时出错!\n" + e.getMessage(), e);
//  }
  return con;

 }

 /**
  * 关闭数据源连接
  */
 public void closeConnection() throws InsigmaException {
  Connection con = null;
  try {
   con = getDataSource().getConnection();
   if (con != null) {
    con.close();
   }
  } catch (SQLException e) {
//   e.printStackTrace();
   throw new InsigmaException("关闭数据源连接时出错!\n" + e.getMessage(), e);
  }

 }

 /**
  * 得到Hibernate的Session
  *
  * @return Session
  */
 public Session getHSession() throws InsigmaException {
  Session s = getHibernateTemplate().getSessionFactory().openSession();
  return s;
 }

 /**
  * 关闭Hibernate的Session
  *
  * @param s
  *            Session
  * @throws InsigmaException
  */
 public void closeHSession(Session s) throws InsigmaException {
  if (s != null) {
   s.close();
  }
 }

 /**
  * 关闭输入的连接
  */
 public void closeConnection(Connection conn) throws InsigmaException {

  try {

   if (conn != null) {
    conn.close();
   }
  } catch (SQLException e) {
//   e.printStackTrace();
   throw new InsigmaException("关闭连接时出错!\n" + e.getMessage(), e);
  }

 }

 /**
  * 执行存储过程
  *
  * @param proc
  *            如:
  */
 public void runProc(String proc) throws InsigmaException {
  Connection conn = null;
  Statement st = null;
  Session ses = getSession();
  try {
   conn = ses.connection();
   st = conn.createStatement();
   st.execute("{call " + proc + "}");
  } catch (Exception e) {
//   e.printStackTrace();
   throw new InsigmaException("执行存储过程时出错!\n" + e.getMessage(), e);
  } finally {
   try {
    if (st != null) {
     st.close();
    }
    if (conn != null) {
     conn.close();
    }
    releaseSession(ses);
   } catch (SQLException e) {
//    e.printStackTrace();
    throw new InsigmaException("关闭数据连接出错!\n" + e.getMessage(), e);
   }
  }
 }

  public Object load(String hql) throws InsigmaException {
    Session ses = getSession();
    Query q = ses.createQuery(hql);
    return q.uniqueResult();
  }

 /* (non-Javadoc)
  * @see com.insigma.common.dao.HibernateBaseDao#findObjs(org.hibernate.criterion.DetachedCriteria)
  */
 public List findObjs(DetachedCriteria criteria) throws InsigmaException {
  // TODO Auto-generated method stub
  List list = getHibernateTemplate().findByCriteria(criteria);
  return list;
 }

 /* (non-Javadoc)
  * @see com.insigma.common.dao.HibernateBaseDao#findObjs(org.hibernate.criterion.DetachedCriteria, int, int)
  */
 public List findObjs(DetachedCriteria criteria, int first, int max)
   throws InsigmaException {
  // TODO Auto-generated method stub
  List list = getHibernateTemplate().findByCriteria(criteria, first, max);
  return list;
 }
}

推荐阅读