对hibernate的封装 HibernateTemplate

本文提供了一套针对Hibernate操作的封装方案,包括增删改查等基本功能,并实现了分页查询等功能。
使用hibernate也有很久一段时间了,做了点简单的封装:

package org.jutil.hibernate.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

public abstract class HibernateTemplate<T extends Object> {

private static HibernateUtil util = HibernateUtil.getInstance();

/**
* 获得接口中泛型的实例
*
* @param index
* @return
*/
@SuppressWarnings("unchecked")
private Class getGenericType(int index) {
Type genType = getClass().getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
throw new RuntimeException("Index outof bounds");
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}

/**
* 保存对象
* @param entity
*/
public void save(Object entity) {
Session s = null;
Transaction tx = null;
try {
s = util.getSession();
tx = s.beginTransaction();
s.save(entity);
tx.commit();
} finally {
if (s != null)
util.closeSession(s);
}
}

/**
* 删除对象
* @param entity
*/
public boolean delete(Object entity) {
Session s = null;
Transaction tx = null;
try {
s = util.getSession();
tx = s.beginTransaction();
s.delete(entity);
tx.commit();
return true;
}catch (Exception e) {
return false;
} finally {
if (s != null)
util.closeSession(s);
}
}

/**
* 删除对象
* @param entityName
* @param object
* @return
*/
public boolean delete(String entityName, Object object) {
Session s = null;
Transaction tx = null;
try {
s = util.getSession();
tx = s.beginTransaction();
s.delete(entityName, object);
tx.commit();return true;
}catch (Exception e) {
return false;
} finally {
if (s != null) {
util.closeSession(s);
}
}
}

/**
* 更新对象
* @param entity
*/
public void update(Object entity) {
Session s = null;
Transaction tx = null;
try {
s = util.getSession();
tx = s.beginTransaction();
s.update(entity);
tx.commit();
} finally {
if (s != null)
util.closeSession(s);
}
}

/**
* get 方式获得对象
* @param id 在hibernate中作为主键的值
* @return
*/
@SuppressWarnings("unchecked")
public T get(Serializable id) {
Class clazz = getGenericType(0);
Session s = null;
try {
s = util.getSession();
Object obj = s.get(clazz, id);
return (T) obj;
} finally {
if (s != null)
util.closeSession(s);
}
}

/**
* get 方式获得对象
* @param id 在hibernate中作为主键的值
* @return
*/
@SuppressWarnings("unchecked")
public T get(Class clazz ,Serializable id) {
Session s = null;
try {
s = util.getSession();
Object obj = s.get(clazz, id);
return (T) obj;
} finally {
if (s != null)
util.closeSession(s);
}
}

/**
* get 方式获得对象
* @param id 在hibernate中作为主键的值
* @return
*/
@SuppressWarnings("unchecked")
public T get(String entityName,Serializable id) {
Session s = null;
try {
s = util.getSession();
Object obj = s.get(entityName, id);
return (T) obj;
} finally {
if (s != null)
util.closeSession(s);
}
}

/**
* load 方式获得对象
* @param id 在hibernate中作为主键的值
* @return
*/
@SuppressWarnings("unchecked")
public T load(Serializable id) {
Class clazz = getGenericType(0);
Session s = null;
try {
s = util.getSession();
Object obj = s.load(clazz, id);
return (T) obj;
} finally {
if (s != null)
util.closeSession(s);
}
}

/**
* load 方式获得对象
* @param clazz
* @param id 在hibernate中作为主键的值
* @return
*/
@SuppressWarnings("unchecked")
public T load(Class clazz ,Serializable id) {
Session s = null;
try {
s = util.getSession();
Object obj = s.load(clazz, id);
return (T) obj;
} finally {
if (s != null)
util.closeSession(s);
}
}

/**
* load 方式获得对象
* @param entityName 实体类全名称
* @param id 在hibernate中作为主键的值
* @return
*/
@SuppressWarnings("unchecked")
public T load(String entityName,Serializable id) {
Session s = null;
try {
s = util.getSession();
Object obj = s.load(entityName, id);
return (T) obj;
} finally {
if (s != null)
util.closeSession(s);
}
}

/**
* 根据(HQL: Hibernate查询语言)得到唯一对象,语句查询结果必须只有一条结果,否则抛出异常
* @param sql 查询语句
* @return T
*/
@SuppressWarnings("unchecked")
public T uniqueResult(String sql){
sqlValidate(sql);
Query query = util.getSession().createQuery(sql);
return (T) query.uniqueResult();
}

/**
* 根据(数据库的Native SQL语言)得到唯一对象,语句查询结果必须只有一条结果,否则抛出异常
* @param sql 查询语句
* @return Object[] 封装后的结果
*/
public Object[] uniqueResultSQL(String sql){
sqlValidate(sql);
SQLQuery query = util.getSession().createSQLQuery(sql);
return (Object[]) query.uniqueResult();
}

/**
* 根据(HQL: Hibernate查询语言)查询所有符合条件的记录,并将结果封装到List<T> 中
* @param sql 查询语句
* @param args 参数
* @return List<T>
*/
@SuppressWarnings("unchecked")
public List<T> findByQuery(String sql, Object... args) {
try {
sqlValidate(sql);
Query query = util.getSession().createQuery(sql);
for (int i = 0; i < args.length; i++) {
query.setParameter(i, args[i]);
}
return query.list();
} catch (Exception e) {
throw new HibernateException(e.getMessage());
}
}

/**
* 根据(Native SQL查询语言)查询所有符合条件的记录List
* @param sql 查询语句
* @param args 参数
* @return List
*/
@SuppressWarnings("unchecked")
public List findBySQLQuery(String sql,Object ... args) {
try {
sqlValidate(sql);
SQLQuery query = util.getSession().createSQLQuery(sql);
for (int i = 0; i < args.length; i++) {
query.setParameter(i, args[i]);
}
return query.list();
} catch (Exception e) {
throw new HibernateException(e.getMessage());
}
}

/**
*根据(Native SQL查询语言)查询所有符合条件的记录,并将结果封装到List<Object[]> 中
* @param sql 查询语句
* @param args 参数
* @return List<Object[]> 封装后的结果
*/
@SuppressWarnings("unchecked")
public List<Object[]> findBySQLQueryToList(String sql,Object ... args) {
try {
sqlValidate(sql);
List<Object[]> result = new ArrayList<Object[]>(0);
Object[] temp = null;
SQLQuery query = util.getSession().createSQLQuery(sql);
for (int i = 0; i < args.length; i++) {
query.setParameter(i, args[i]);
}
List r = query.list();
Iterator ite = r.iterator();
while(ite.hasNext()){
temp = (Object[]) ite.next();
System.out.println(temp[0]+":"+temp[1]+":"+temp[2]);
result.add(temp);
}
return result;
} catch (Exception e) {
throw new HibernateException(e.getMessage());
}
}

/**
* 得到符合条件的总记录数
* @param query
* @return Integer
*/
@SuppressWarnings("unchecked")
private Integer getTotalSize(Query query){
List temp = query.list();
Integer totalSize = temp.size();
temp.clear();
temp = null;
return totalSize;
}

/**
* 根据(HQL: Hibernate查询语言)查询所有符合条件的记录,封装到Page对象中,page 中list 泛型为 T
* @param sql 查询语句
* @param pageNo 页码
* @param pageSize 每页大小
* @param args 参数
* @return Page 封装着分页查询结果对象和一些信息的对象
*/
@SuppressWarnings("unchecked")
public Page pageQueryByPageNO(String sql,Integer pageNo,Integer pageSize,Object ...args) {
try {
sqlValidate(sql);
Query query = util.getSession().createQuery(sql);
for(int i=0;i<args.length;i++){
query.setParameter(i, args[i]);
}
Integer totalSize = getTotalSize(query);
Integer start = (pageNo-1)*pageSize;
query.setFirstResult(start);
query.setMaxResults(pageNo*pageSize);
List<T> data = query.list();
return new Page<T>(start, totalSize,pageSize, data);
} catch (Exception e) {
throw new HibernateException(e.getMessage());
}
}

/**
* 根据(Native SQL查询语言)查询所有符合条件的记录,封装到Page对象中,page 中list 泛型为 OBject[]
* @param sql 查询语句
* @param pageNo 页码
* @param pageSize 每页大小
* @param args 参数
* @return Page 封装着分页查询结果对象和一些信息的对象
*/
@SuppressWarnings("unchecked")
public Page pageSQLQueryByPageNO(String sql,Integer pageNo,Integer pageSize,Object ...args) {
try {
sqlValidate(sql);
List<Object[]> result = new ArrayList<Object[]>(0);
Object[] temp = null;
SQLQuery query = util.getSession().createSQLQuery(sql);
for (int i = 0; i < args.length; i++) {
query.setParameter(i, args[i]);
}
Integer totalSize = getTotalSize(query);
Integer start = (pageNo-1)*pageSize;
query.setFirstResult(start);
query.setMaxResults(pageNo*pageSize);
List r = query.list();
Iterator ite = r.iterator();
while(ite.hasNext()){
temp = (Object[]) ite.next();
result.add(temp);
}
return new Page<Object[]>(start,totalSize,pageSize, result);
} catch (Exception e) {
throw new HibernateException(e.getMessage());
}
}

/**
* 验证sql不为null||''
* @param sql
*/
private void sqlValidate(String sql) {
if (sql == null || sql.trim().length() < 0) {
throw new RuntimeException("sql sentence is null or is '' ");
}
}

}



[color=darkred]HibernateUtil [/color]


package org.jutil.hibernate.base;

import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.Properties;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.w3c.dom.Document;

@SuppressWarnings("serial")
public class HibernateUtil implements Serializable {

private static SessionFactory factory = null;
private static HibernateUtil util = null;

public static HibernateUtil getInstance(){
if(util == null){
util = new HibernateUtil();
}
return util;
}

private HibernateUtil(){
try {
Configuration cfg = new Configuration().configure();
factory = cfg.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}

public static HibernateUtil getInstance(String resource,String ...files){
if(util == null){
util = new HibernateUtil(resource,files);
}
return util;
}

private HibernateUtil(String resource,String ...files){
try {
Configuration cfg = new Configuration();
if(files.length>0){
for(String f:files){
cfg.addFile(f);
}
}
factory = cfg.configure(resource).buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}

public static HibernateUtil getInstance(File configFile,File ...files){
if(util == null){
util = new HibernateUtil(configFile,files);
}
return util;
}

private HibernateUtil(File configFile,File ...files){
try {
Configuration cfg = new Configuration();
if(files.length>0){
for(File f:files){
cfg.addFile(f);
}
}
factory = cfg.configure(configFile).buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}

public static HibernateUtil getInstance(URL url,URL ...urls){
if(util == null){
util = new HibernateUtil(url,urls);
}
return util;
}

private HibernateUtil(URL url,URL ...urls){
try {
Configuration cfg = new Configuration();
for(URL u :urls){
cfg.addURL(u);
}
factory = cfg.configure(url).buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}

public static HibernateUtil getInstance(Document document,Document ...docs){
if(util == null){
util = new HibernateUtil(document,docs);
}
return util;
}

private HibernateUtil(Document document,Document ...docs){
try {
Configuration cfg = new Configuration();
for(Document doc :docs){
cfg.addDocument(doc);
}
factory = cfg.configure(document).buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}

public static HibernateUtil getInstance(InputStream inputStream,InputStream ...inputStreams){
if(util == null){
util = new HibernateUtil(inputStream,inputStreams);
}
return util;
}

private HibernateUtil(InputStream inputStream,InputStream ...inputStreams){
try {
Configuration cfg = new Configuration();
cfg.addInputStream(inputStream);
for(InputStream input :inputStreams){
cfg.addInputStream(input);
}
factory = cfg.configure().buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}

public static HibernateUtil getInstance(Properties extraProperties,Properties ...properties){
if(util == null){
util = new HibernateUtil(extraProperties,properties);
}
return util;
}

private HibernateUtil(Properties extraProperties,Properties ...properties){
try {
Configuration cfg = new Configuration();
cfg.addProperties(extraProperties);
for(Properties propertie :properties){
cfg.addProperties(propertie);
}
factory = cfg.configure().buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}

@SuppressWarnings("unchecked")
public static HibernateUtil getInstance(Class persistentClass,Class ...classes){
if(util == null){
util = new HibernateUtil(persistentClass,classes);
}
return util;
}

@SuppressWarnings("unchecked")
private HibernateUtil(Class persistentClass,Class ...classes){
try {
Configuration cfg = new Configuration();
cfg.addClass(persistentClass);
for(Class clss :classes){
cfg.addClass(clss);
}
factory = cfg.configure().buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}

public SessionFactory getSessionFactory() {
return factory;
}

public Session getSession() {
return factory.openSession();
}

public void closeSession(Session session) {
if (session != null) {
if (session.isOpen()) {
session.close();
}
}
}

}



用于分页的Page对象


package org.jutil.hibernate.base;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Page<T> {

private static final long serialVersionUID = 2728437513842150372L;
private static final int DEFAULT_PAGE_SIZE = 10;
private int start;
private List<T> data;
private long totalCount;
private int pageSize = DEFAULT_PAGE_SIZE;

public Page() {
this(0, 0L, Page.DEFAULT_PAGE_SIZE, ((List<T>) (new ArrayList<T>())));
}

public Page(int pageSize) {
this(0, 0L, pageSize, ((List<T>) (new ArrayList<T>())));
}

public Page(int start, long totalSize, int pageSize, List<T> data) {
if (pageSize <= 0 || start < 0 || totalSize < 0L) {

} else {
this.pageSize = pageSize;
this.start = start;
totalCount = totalSize;
this.data = data;
return;
}
}

public long getTotalCount() {
return totalCount;
}

public long getTotalPageCount() {
return totalCount % (long) pageSize != 0L ? totalCount/ (long) pageSize + 1L: totalCount/ (long) pageSize;
}

public void setResult(List<T> data) {
this.data = data;
}

public List<T> getResult() {
return data;
}

public int getCurrentPageNo() {
return start / pageSize + 1;
}

public boolean hasNextPage() {
return (long) getCurrentPageNo() < getTotalPageCount();
}

public boolean hasPreviousPage() {
return getCurrentPageNo() > 1;
}

public boolean isEmpty() {
return data == null || data.isEmpty();
}

public int getStartIndex() {
return (getCurrentPageNo() - 1) * pageSize;
}

public int getEndIndex() {
int endIndex = getCurrentPageNo() * pageSize - 1;
return (long) endIndex < totalCount ? endIndex : (int) totalCount - 1;
}

protected static int getStartOfPage(int pageNo) {
return getStartOfPage(pageNo, 20);
}

public static int getStartOfPage(int pageNo, int pageSize) {
return (pageNo - 1) * pageSize;
}

public int getPageSize() {
return pageSize;
}

public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}

}



[color=darkred]最后再附上所有的源码 和测试代码及配置文件。[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值