标签:
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();
}
}
}
标签:
原文地址:http://www.cnblogs.com/chengfeifei/p/4702921.html