首页 > 代码库 > Hibernate工具类
Hibernate工具类
package com.cjq.util;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public final class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil() {
}
static {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
/**
* 得到会话工厂
*
* @return
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* 查询方法
*/
public static List executeQuery(String hql, String[] parameters) {
Transaction tx = null;
Session session = null;
List list = null;
try {
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
Query query = session.createQuery(hql);
if (parameters != null && parameters.length > 0) {
for (int i = 0; i < parameters.length; i++) {
query.setString(i, parameters[i]);
}
}
list = query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw new RuntimeException(e.getMessage());
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return list;
}
/**
* 添加
*/
public static void saveObject(Object obj) {
Transaction tx = null;
Session session = null;
try {
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
session.save(obj);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
throw new RuntimeException(e.getMessage());
}
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
/**
* 修改删除方法
*
* @param hql
* @param parameters
*/
public static void excuteUpdate(String hql, String[] parameters) {
Transaction tx = null;
Session session = null;
try {
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
Query query = session.createQuery(hql);
if (parameters != null && parameters.length > 0) {
for (int i = 0; i < parameters.length; i++) {
query.setString(i, parameters[i]);
}
}
query.executeUpdate();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
throw new RuntimeException(e.getMessage());
}
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
/**
* 分页
*/
public static List excuteQueryByPaginPage(String hql, String[] parameters,
int pageSize, int pageNow) {
Transaction tx = null;
Session session = null;
List list = null;
try {
session = sessionFactory.getCurrentSession();
tx = session.beginTransaction();
Query query = session.createQuery(hql);
if (parameters != null && parameters.length > 0) {
for (int i = 0; i < parameters.length; i++) {
query.setString(i, parameters[i]);
}
}
query.setFirstResult((pageNow - 1) * pageSize).setMaxResults(
pageSize);
query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
throw new RuntimeException(e.getMessage());
}
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return list;
}
}
Hibernate工具类