码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate之单表类型数据处理泛型类

时间:2015-08-04 20:42:23      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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();
}

}

}

Hibernate之单表类型数据处理泛型类

标签:

原文地址:http://www.cnblogs.com/chengfeifei/p/4702921.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!