Hibernate4 HibernateSessionFactory


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateSessionFactory {
	    //指定Hibernate配置文件路径
        private static String CONFIG_FILE_LOCATON="/hibernate.cfg.xml";
        //创建ThreadLocal
        private static final ThreadLocal<Session> sessionThreadLocal=
        		new ThreadLocal<Session>();
        //创建Configuration对象
        private static Configuration configuration=new Configuration();
        //定义Session对象
        private static SessionFactory sessionFactory;
        //定义configFile属性并赋值
        private static String ConfigFile =CONFIG_FILE_LOCATON;
        static{
        	try{
        		//读取配置文件Hibernate.cfg.xml
        		//configuration.configure()默认在classpath下寻找Hibernate文件
        		/*所有基于Hibernate的配置或者服务都必须统一向这个ServiceRegistry注册后才能生效。
        		所以不难看出 Hibernate4的配置入口不再是Configuration对象,而是ServiceRegistry对象,Configuration对象将通过ServiceRegistry对象获取配置信息。
        		使用了Builder模式创建一个ServiceRegistry对象,可以看到源码org.hibernate.service.ServiceRegistryBuilder这个类。*/
        		configuration.configure();
        		//生成一个注册机对象
        		ServiceRegistry serviceRegistry=
        				new ServiceRegistryBuilder().applySettings(configuration.getProperties())
        				.buildServiceRegistry();
        		//使用注册机对象ServiceRegistry创建SessionFactory
        		sessionFactory=
        		  configuration.buildSessionFactory(serviceRegistry);
        	}
        	catch (Exception e) {
				e.printStackTrace();
			}
        }
        //创建无参的HibernateSessionFactory构造方法
        	public static SessionFactory getSessionFactory(){
        		return sessionFactory;
        	}
        	//重建SessionFactory
        	public static void rebuildSessionFactory(){
        		synchronized (sessionFactory) {
        			try{
        				configuration.configure(ConfigFile);
        				ServiceRegistry serviceRegistry=new ServiceRegistryBuilder()
        				.applySettings(configuration.getProperties()).buildServiceRegistry();
        				sessionFactory = configuration.buildSessionFactory(serviceRegistry);
				}
        			catch (Exception e) {
						e.printStackTrace();
					}
        	
        
        	}
        }
            //获得session
        	public static Session getSession(){
        		Session session=(Session)sessionThreadLocal.get();
        		try{
        			if(session==null|| !session.isOpen()){
        				if(sessionFactory==null){
        					rebuildSessionFactory();
        				}
        			}
        	
        		session = (sessionFactory!=null)?
        				sessionFactory.openSession() : null;
        		sessionThreadLocal.set(session);
        		}
        		catch (Exception e) {
        			e.printStackTrace();
					
        		}
        		return session;
        		
        	}
        //必须手动关闭
        	public static void closeSession(){
        		Session session=(Session)sessionThreadLocal.get();
        		sessionThreadLocal.set(null);
        		try {
					if(session!=null&&session.isOpen())
					{
						session.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
        	}
        	//configFile属性的set方法
        	public static void setConfigFile(String configFile){
        		HibernateSessionFactory.ConfigFile=configFile;
        		sessionFactory=null;
        	}
        	//configuration的get方法
        	public static Configuration getConfiguration(){
        		return configuration;
        	}
        	
        
        
}

增删改查操作


import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

import com.hibtest2.HibernateSessionFactory;

public class BaseHibernateDAO {
	/**
	 * 添加数据
	 * @param object
	 */
	protected void add(Object object){
		Transaction tran=null;
		//获取session
		Session session=HibernateSessionFactory.getSession();
		try{
			//开始事务
			tran=session.beginTransaction();
			//持久化操作
		    session.save(object);
		    //提交事务
		    tran.commit();
		}catch (Exception e) {
			if(tran!=null){
				//事务回滚
				tran.rollback();
			}
			e.printStackTrace();
		}finally{
			//关闭session
			HibernateSessionFactory.closeSession();
		}		
	}		
	/**
	 * 加载数据
	 * @param cla
	 * @param id
	 * @return
	 */
	protected Object get(Class cla,Serializable id){
		Object object=null;
		Session session=HibernateSessionFactory.getSession();
		try{
			object=session.get(cla, id);
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
		return object;
	}		
	/**
	 * 删除数据
	 * @param object
	 */
	protected void delete(Object object){
		Transaction tran=null;
		Session session=HibernateSessionFactory.getSession();
		try{
			tran=session.beginTransaction();
		    session.delete(object);
		    tran.commit();
		}catch (Exception e) {
			if(tran!=null){
				tran.rollback();
			}
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}		
	/**
	 * 修改数据
	 * @param object
	 */
	protected void update(Object object){
		Transaction tran=null;
		Session session=HibernateSessionFactory.getSession();
		try{
			tran=session.beginTransaction();
		    session.update(object);
		    tran.commit();
		}catch (Exception e) {
			if(tran!=null){
				tran.rollback();
			}
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
	
	
	//组合查询
	protected List search(Class cla,Object condition){
		Session session=null;
		List list=null;
		try {
			session=HibernateSessionFactory.getSession();		
			list=session.createCriteria(cla).add(Example.create(condition)).list();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			HibernateSessionFactory.closeSession();
		}
		return list;	
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值