package chengfei.hibernate.Dao;
import java.util.List;import org.hibernate.HibernateException;import org.hibernate.session;import org.hibernate.Transaction;import chengfei.hibernate.tool.HibernateUtils;
/**hibernate數據庫操作泛型類 * @author Administrator * @param <T> */public class service<T> {
PRivate Class<T> c;
public service(Class<T> c) {this.c = c;}
/**保存 * @param t */public void save(T t) { Session session = HibernateUtils.openSession();Transaction tx = null;try {tx = session.beginTransaction();session.save(t);tx.commit();
} catch (HibernateException e) {tx.rollback();throw e;} finally {session.close();}}
/**刪除 * @param id */public void delete(Integer id) {Session session = HibernateUtils.openSession();Transaction tx = null;try {tx = session.beginTransaction();T t = this.getById(id);session.delete(t);tx.commit();} catch (HibernateException e) {tx.rollback();throw e;} finally {session.close();}
}
/**更新 * @param t */public void update(T t) {Session session = HibernateUtils.openSession();Transaction tx = null;try {tx = session.beginTransaction();session.update(t);tx.commit();} catch (HibernateException e) {tx.rollback();throw e;} finally {session.close();}
}
/**得到唯一對象 * @param id * @return */@SuppressWarnings("unchecked")public T getById(Integer id) { Session session = HibernateUtils.openSession();Transaction tx = null;try {tx = session.beginTransaction();T t = (T) session.get(c, id);tx.commit();return t;} catch (HibernateException e) {tx.rollback();throw e;} finally {session.close();}}
/**獲得所有 * @return */@SuppressWarnings("unchecked")public List<T> FindAll() {Session session = HibernateUtils.openSession();Transaction tx = null;try {tx = session.beginTransaction();List<T> list = session.createQuery("from " + c.getSimpleName()).list();tx.commit();return list;} catch (HibernateException e) {tx.rollback();throw e;} finally {session.close();}}
/**獲得分頁的數據 * @param firstResult * @param maxresult * @return */@SuppressWarnings({ "unchecked", "rawtypes" })public QueryResult FindAll(int firstResult, int maxresult) {Session session = HibernateUtils.openSession();Transaction tx = null;try {tx = session.beginTransaction();List<T> list = session.createQuery(//"from " + c.getSimpleName())//.setFirstResult(firstResult)//.setMaxResults(maxresult).list();tx.commit();Long count = (Long) session.createQuery("select count(*) from " + c.getSimpleName())//.uniqueResult();return new QueryResult(list, count.intValue());} catch (HibernateException e) {tx.rollback();throw e;} finally {session.close();}
}
}
新聞熱點
疑難解答