Hibernate用到的CommonDao(包括分頁)

package org.accp.house.dao.hbimpl;

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

import org.accp.house.dao.IHibernateCallback;
import org.accp.house.hibernateutil.HibernateSessionFactory;
import org.accp.house.pager.Condition;
import org.accp.house.pager.Direct;
import org.accp.house.pager.Order;
import org.accp.house.pager.PageInfo;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

@SuppressWarnings("unchecked")
public class CommonDao<T extends Serializable> {

private Class<T> classzz;

public CommonDao() {
  // TODO Auto-generated constructor stub
}

public CommonDao(Class<T> classzz) {
  // TODO Auto-generated constructor stub
  this.classzz = classzz;
}

/**保存一個臨時對象[用戶]*/

public void persist(T obj) {
  // TODO Auto-generated method stub
  Session session = null;
  Transaction ts = null;
 
  try {
   session = HibernateSessionFactory.getSession();
   ts = session.beginTransaction();
  
   session.save(obj);
  
   ts.commit();
  } catch(Exception e){
   ts.rollback();
   throw new RuntimeException(e.getMessage());
  } finally {
   if (session!=null) session.close();
  }
 
}


public void remove(T obj) {
  // TODO Auto-generated method stub
  Session session = null;
  Transaction ts = null;
 
  try {
   session = HibernateSessionFactory.getSession();
   ts = session.beginTransaction();
  
   session.delete(obj);
  
   ts.commit();
  } catch(Exception e){
   ts.rollback();
   throw new RuntimeException(e.getMessage());
  } finally {
   if (session!=null) session.close();
  }
}


public void update(T obj) {
  // TODO Auto-generated method stub
  Session session = null;
  Transaction ts = null;
 
  try {
   session = HibernateSessionFactory.getSession();
   ts = session.beginTransaction();
  
   session.update(obj);
  
   ts.commit();
  } catch(Exception e){
   ts.rollback();
   throw new RuntimeException(e.getMessage());
  } finally {
   if (session!=null) session.close();
  }
 
}

public T getObject(Serializable oid){
  Session session = null;
  try {
   session = HibernateSessionFactory.getSession();
   return (T)session.get(classzz, oid);
  } catch (Exception e) {
   throw new RuntimeException(e.getMessage());
  } finally {
   if (session!=null) session.close();
  }
}


public List<T> findAll() {
  // TODO Auto-generated method stub
  Session session = null;
  try {
   session = HibernateSessionFactory.getSession();
   return session.createCriteria(classzz).list();
  } catch (Exception e) {
   throw new RuntimeException(e.getMessage());
  } finally {
   if (session!=null) session.close();
  }
}

public List<T> findByProperties(Condition...conditions){
  if (conditions==null || conditions.length==0){
   return findAll();
  }
 
  Session session = null;
  try {
   session = HibernateSessionFactory.getSession();
   Criteria qbc = session.createCriteria(classzz);
   prepareCondition(qbc,conditions);
   return qbc.list();
  } catch (Exception e) {
   throw new RuntimeException(e.getMessage());
  } finally {
   if (session!=null) session.close();
  }
}
 

public void pager(final PageInfo pi){
  if (pi==null || pi.getClasszz()==null){
   throw new RuntimeException("分頁基本條件不全");
  }
 
  execute(new IHibernateCallback() {
  
   @Override
   public Object doInHibernate(Session session) {
    Criteria qbc = session.createCriteria(pi.getClasszz());
    //1.設置條件
//   
     List<Condition> list = pi.getConditions();
   
    prepareCondition(qbc,list.toArray(new Condition[]{}));
   
    //2.計算總條數
    qbc.setProjection(Projections.rowCount());
    pi.setRecordCount(
      (Integer)qbc.uniqueResult()
    );
    //3.總頁數
    pi.setPageCount(
      pi.getRecordCount()%pi.getPageSize()==0?
        pi.getRecordCount()/pi.getPageSize():
         pi.getRecordCount()/pi.getPageSize()+1
    );
    //4.清空投影查詢的設置
    qbc.setProjection(null);
    //5.處理排序
    prepareOrder(qbc,((List<Order>)pi.getOrders()).toArray(new Order[]{}));
    //6.獲得分頁結果
    pi.setResult(
      qbc
       .setFirstResult((pi.getPageIndex()-1)*pi.getPageSize())
       .setMaxResults(pi.getPageSize())
       .list()
    );
    return null;
   }
  });
 
}

public Object execute(IHibernateCallback hibernateCallback){
  Session session = null;
  Transaction ts = null;
  Object result = null;
  try {
   session = HibernateSessionFactory.getSession();
   ts = session.beginTransaction();
  
   if (hibernateCallback!=null)
    result = hibernateCallback.doInHibernate(session);
  
   ts.commit();
  } catch(Exception e){
   ts.rollback();
   throw new RuntimeException(e.getMessage());
  } finally {
   if (session!=null) session.close();
  }
 
  return result;
}

private void prepareCondition(Criteria qbc,Condition...conditions){
  if (conditions==null || conditions.length==0)
   return;
 
  for (Condition cdt : conditions) {
   switch (cdt.getCp()) {
   case EQ:
qbc.add(Restrictions.eq(cdt.getPropertyName(), cdt.getPropertyValue()));
    break;    
   case GT:
    qbc.add(Restrictions.gt(cdt.getPropertyName(), cdt.getPropertyValue()));
    break;    
   case LT:
    qbc.add(Restrictions.lt(cdt.getPropertyName(), cdt.getPropertyValue()));
    break;
   case GE:
    qbc.add(Restrictions.ge(cdt.getPropertyName(), cdt.getPropertyValue()));
    break;
   case LE:
    qbc.add(Restrictions.le(cdt.getPropertyName(), cdt.getPropertyValue()));
    break;
   case LIKE:
    qbc.add(Restrictions.like(cdt.getPropertyName(), cdt.getPropertyValue().toString(), MatchMode.ANYWHERE));
    break;
   default:
    break;
   }
  }
}

private void prepareOrder(Criteria qbc,Order...orders){
 
  if (orders==null || orders.length==0)
   return;
 
  for (Order ord : orders) {
   qbc.addOrder(
     ord.getDirect()==Direct.ASC?
       org.hibernate.criterion.Order.asc(ord.getPropertyName()):
        org.hibernate.criterion.Order.desc(ord.getPropertyName())
    );
  }
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章