首页 > 代码库 > Hibernate的一种用法

Hibernate的一种用法

废话不多说,上代码
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;

import com.HomeFurnishing.common.Exceptions.MyRuntimeException;
import com.HomeFurnishing.common.entity.PageCond;


/***
 * @author zhukovasky
 * @version 1.0
 * @see 本接口用来做一般的增删改查适合于Hibernate框架,做单表操作可能会存在一些问题
 * */
public interface HibernateDAO {
	/***
	 * 保存,单表操作
	 * */
	public void saveEntity(String klass,Object obj);
	public void updateEntity(String klass,Object obj);
	public void insertEntity(String klass,Object obj);
	public void deleteEntity(String klass,Object obj);
	public void deleteEntityByCascade(String klass,Object[] obj);
	public List queryEntitiesByCriteria(Criterion criteria, String klass,List<Order> orders);
	public List queryEntitiesByTemplate(String klass,Object obj,Criterion criteria ,List<Order> orders);
	
	public Object[] queryEntitiesByCriteria(Criterion criteria, String klass,PageCond page,List<Order> orders);
	/***
	 * @author zhukovasky
	 * @see 模板查询
	 * */
	public Object[] queryEntitiesByTemplate(String klass,Object obj,Criterion criteria ,PageCond page,List<Order> orders);
	
	public <V> V expandEntity(String klass,V obj);
	/****
	 * @author zhukovasky
	 * @param sqlLocations 放置sql相应路径名
	 * @see i.e.String packagename="com.zhukovasky.common.utils";
	 * 			String xmlname="testxml.xml"
	 * 			String sqlname="queryMyBudget"; 
	 * 			那么它的值应该是
	 * 			"com.zhukovasky.common.utils.testxml.queryMyBudget"
	 * 			程序会自动计算相应的地址并生成实际的路径名
	 * @param Map<String,Object> parameterMap 查询参数
	 * @return List<Map> 返回结果为HashMap,对于单条记录
	 * 
	 * */
	public List<Map> queryNameSqlByHibernate(String sqlLocations,Map<String,Object> parameterMap) throws MyRuntimeException;
	/**
	 * @author zhukovasky
	 * @param sqlLocations 放置sql相应路径名
	 * @see i.e.String packagename="com.zhukovasky.common.utils";
	 * 			String xmlname="testxml.xml"
	 * 			String sqlname="queryMyBudget"; 
	 * 			那么它的值应该是
	 * 			"com.zhukovasky.common.utils.testxml.queryMyBudget"
	 * 			程序会自动计算相应的地址并生成实际的路径名
	 * @param Map<String,Object> parameterMap 查询参数
	 * @return List<Map> 返回结果为HashMap,对于单条记录
	 * 
	 * */
	public List<Map> queryNameSqlByHibernate(String sqlLocations,Map<String,Object> parameterMap,PageCond page) throws MyRuntimeException;
	/***
	 * @author zhukovasky
	 * @param sqlLocations 放置存储过程位置
	 * */
	public void callProcedures(String sqlLocations,Map<String,Object> parameterMap);
}

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import org.hibernate.Criteria;
import org.hibernate.EntityMode;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import com.HomeFurnishing.common.DataBaseUtil.basic.HibernateSessionFactory;
import com.HomeFurnishing.common.Exceptions.MyRuntimeException;
import com.HomeFurnishing.common.Pagination.Pagination;
import com.HomeFurnishing.common.XmlUtils.XmlUtils;
import com.HomeFurnishing.common.entity.PageCond;

public class HibernateDAOImpl implements HibernateDAO {
	private static final Logger log = LoggerFactory.getLogger(HibernateDAOImpl.class);
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * @see 该方法可能在实体没有sequence的情况下使用会有些问题
	 * */
	public void saveEntity(String klass, Object obj) {
		if(obj==null){
			log.error("saveEntity方法对象为空!");
		}
		Session session=HibernateSessionFactory.getSessionFactory().openSession();
		log.info("保存实体");
		session.save(klass, obj);
		session.flush();
		
	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * */
	
	public void updateEntity(String klass, Object obj) {
		Session session=HibernateSessionFactory.getSessionFactory().openSession();
		
		session.update(klass, obj);
		session.flush();
	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * */

	public void insertEntity1(String klass, Object obj) {
		Session session=HibernateSessionFactory.getSessionFactory().openSession();
		
		session.save(klass, obj);
		session.flush();
	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * */

	public void deleteEntity(String klass, Object obj) {
		// TODO Auto-generated method stub

	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * */

	public void deleteEntityByCascade(Class klass, Object[] obj) {
		// TODO Auto-generated method stub

	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * */

	public List queryEntitiesByCriteria(Criterion criteria, String klass,
			List<Order> orders) {
		// TODO Auto-generated method stub
		return null;
	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * */
	@SuppressWarnings("unchecked")
	public <V> V expandEntity(String klass, V obj) {
		Session session=HibernateSessionFactory.getSessionFactory().openSession();
		ClassMetadata cl=HibernateSessionFactory.getSessionFactory().getClassMetadata(klass);
		Serializable id=cl.getIdentifier(obj, EntityMode.POJO);
		obj=(V) session.get(klass, id);	
		return obj;
	}
	/**
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 */
	public List queryEntitiesByTemplate(String klass, Object obj,
			Criterion criteria, List<Order> orders) {
		Session session=HibernateSessionFactory.getSession();
		Criteria criterias=session.createCriteria(klass).add(Example.create(obj)).add(criteria);
		List list=null;
		if(orders==null){
			list=criterias.list();
		}else{
			for(Order iter:orders){
				criterias.addOrder(iter);
			}
		}
		list=criterias.list();
		return list;
	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * **/
	public void insertEntity(String klass, Object obj) {
		Session session=HibernateSessionFactory.getSessionFactory().openSession();
		session.save(klass, obj);
		session.flush();
	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * */

	public void deleteEntityByCascade(String klass, Object[] obj) {
		// TODO Auto-generated method stub
		
	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * */

	public Object[] queryEntitiesByCriteria(Criterion criteria, String klass,
			PageCond page, List<Order> orders) {
		Object[] result=Pagination.doQueryPageCond(klass, criteria, orders, page);
		return result;
	}
	/***
	 * @param klass 实体名称,类的名称
	 * @param Obj 实体对象
	 * */

	public Object[] queryEntitiesByTemplate(String klass, Object obj,
			Criterion criteria, PageCond page, List<Order> orders) {
		Object[] result=Pagination.doQueryPageCond(klass, criteria, orders, page);
		return result;
	}
	/****
	 * @author zhukovasky
	 * @param sqlLocations 放置sql相应路径名
	 * @see i.e.String packagename="com.zhukovasky.common.utils";
	 * 			String xmlname="testxml.xml"
	 * 			String sqlname="queryMyBudget"; 
	 * 			那么它的值应该是
	 * 			"com.zhukovasky.common.utils.testxml.queryMyBudget"
	 * 			程序会自动计算相应的地址并生成实际的路径名
	 * @param Map<String,Object> parameterMap 查询参数
	 * @return List<Map> 返回结果为HashMap,对于单条记录
	 * 
	 * */
	public List<Map> queryNameSqlByHibernate(String sqlLocations,
			Map<String, Object> parameterMap) throws MyRuntimeException{
		String systempath=System.getProperty("user.dir");
		String realXmlPath=XmlUtils.getRealSqlName(sqlLocations);
		String querySqlname=XmlUtils.getRealSqlName(sqlLocations);
		realXmlPath=systempath+File.separator+"src"+File.separator+realXmlPath;
		String sql="";
		boolean hasExceptions=false;
		Throwable ee=null;
		Session session=null;
		List<Map> result=null;
		try {
			sql=XmlUtils.loadSqlFromXml(realXmlPath, querySqlname, parameterMap);
		} catch (ParserConfigurationException e) {
			log.error("编译XML错误");
			ee=e;
			hasExceptions=true;
		} catch (IOException e){
			log.error("文件读写异常");
			ee=e;
			hasExceptions=true;
		} catch (SAXException e) {
			log.error("解析XML错误");
			ee=e;
			hasExceptions=true;
		}finally{
			if(hasExceptions==true){
				throw new MyRuntimeException(ee);
			}else{
				session=HibernateSessionFactory.getSession();
				SQLQuery sqlquery=session.createSQLQuery(sql);
				String[] RealParameters=sqlquery.getNamedParameters();
				for(String iter:RealParameters){
					if(parameterMap.containsKey(iter)){
						sqlquery.setParameter(iter, parameterMap.get(iter));
					}
				}
				sqlquery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
				result=sqlquery.list();
			}
		}
		return result;
	}
	/****
	 * @author zhukovasky
	 * @param sqlLocations 放置sql相应路径名
	 * @see i.e.String packagename="com.zhukovasky.common.utils";
	 * 			String xmlname="testxml.xml"
	 * 			String sqlname="queryMyBudget"; 
	 * 			那么它的值应该是
	 * 			"com.zhukovasky.common.utils.testxml.queryMyBudget"
	 * 			程序会自动计算相应的地址并生成实际的路径名
	 * @param Map<String,Object> parameterMap 查询参数
	 * @return List<Map> 返回结果为HashMap,对于单条记录
	 * 
	 * */
	public List<Map> queryNameSqlByHibernate(String sqlLocations,
			Map<String, Object> parameterMap, PageCond page)  throws MyRuntimeException{
		String systempath=System.getProperty("user.dir");
		String realXmlPath=XmlUtils.getRealSqlName(sqlLocations);
		String querySqlname=XmlUtils.getRealSqlName(sqlLocations);
		realXmlPath=systempath+File.separator+"src"+File.separator+realXmlPath;
		String sql="";
		boolean hasExceptions=false;
		Throwable ee=null;
		Session session=null;
		List<Map> result=null;
		try {
			sql=XmlUtils.loadSqlFromXml(realXmlPath, querySqlname, parameterMap);
		} catch (ParserConfigurationException e) {
			log.error("编译XML错误");
			ee=e;
			hasExceptions=true;
		} catch (IOException e){
			log.error("文件读写异常");
			ee=e;
			hasExceptions=true;
		} catch (SAXException e) {
			log.error("解析XML错误");
			ee=e;
			hasExceptions=true;
		}finally{
			if(hasExceptions==true){
				throw new MyRuntimeException(ee);
			}else{
				session=HibernateSessionFactory.getSession();
				SQLQuery sqlquery=session.createSQLQuery(sql);
				String[] RealParameters=sqlquery.getNamedParameters();
				for(String iter:RealParameters){
					if(parameterMap.containsKey(iter)){
						sqlquery.setParameter(iter, parameterMap.get(iter));
					}
				}
				sqlquery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
				result=Pagination.doQueryPageCond(sqlquery, page);
			}
		}
		return result;
	}
	
	public void callProcedures(String sqlLocations,
			Map<String, Object> parameterMap) {
		String systempath=System.getProperty("user.dir");
		String realXmlPath=XmlUtils.getRealSqlName(sqlLocations);
		String querySqlname=XmlUtils.getRealSqlName(sqlLocations);
		realXmlPath=systempath+File.separator+"src"+File.separator+realXmlPath;
		String sql="";
		boolean hasExceptions=false;
		Throwable ee=null;
		Session session=null;

		try {
			sql=XmlUtils.loadSqlFromXml(realXmlPath, querySqlname, parameterMap);
		} catch (ParserConfigurationException e) {
			log.error("编译XML错误");
			ee=e;
			hasExceptions=true;
		} catch (IOException e){
			log.error("文件读写异常");
			ee=e;
			hasExceptions=true;
		} catch (SAXException e) {
			log.error("解析XML错误");
			ee=e;
			hasExceptions=true;
		}finally{
			if(hasExceptions==true){
				throw new MyRuntimeException(ee);
			}else{
				session=HibernateSessionFactory.getSession();
				SQLQuery sqlquery=session.createSQLQuery(sql);
				String[] RealParameters=sqlquery.getNamedParameters();
				for(String iter:RealParameters){
					if(parameterMap.containsKey(iter)){
						sqlquery.setParameter(iter, parameterMap.get(iter));
					}
				}
				sqlquery.executeUpdate();
			}
		}
		
	}
	

}

Hibernate的一种用法