Hibernate——Session详解(一)

Hibernate在对资料库进行操作之前,必须先取得Session实例,相当于JDBC在对资料库操作之前,必须先取得Connection实例。

Session是Hibernate对数据库操作的基础,它不是我们所说的JSP页面传递参数的那个Session。Session是Hibernate运作的中心,对象的生命周期、事务的管理、数据库的存取都与session息息相关。

session是线程安全,且由sessionFactory得到。

取得session的前提条件是拿到SessionFactory,下面是Hibernate常用的两种拿到SessionFactory的方式

  1. 得到SessionFactory

方式一:

当在Myeclipse8以上的版本引入Myeclipse自带的Hibernate框架后,myeclipse会自动为项目创建一个HibernateSessionFactory类。

现在对代码进行解析

package com.zhuxuli.HibernateSession;

import javax.persistence.Entity;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
@Entity
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
	
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;
    
	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

然后写一个测试类 test

public static void main(String args[]) {
		Session session = null;
		Transaction tx = null;

		try {
			session = HibernateSessionFactory.getSession();
			tx = session.beginTransaction();
			User user = new User();
			user.setUsername("乔丹");
			user.setUserpass("123");
			session.save(user);
			System.out.println("数据成功写入....");
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			session.close();
		}

	}

可以看到,session直接由HibernateSessionFactory得到。

方式二:

直接在类中读取Hibernate.cfg.xml文件,得到SessionFactory

public static void main(String args[]) {
		Configuration config = new Configuration()
				.configure("/hibernate.cfg.xml");
		SessionFactory sessionFactory = config.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		User user = new User();
		user.setUsername("乔丹");
		user.setUserpass("123");
		session.save(user);
		tx.commit();
	}


以上例子可以看到,得到了SessionFactory后,就可以得到Session,然后对数据进行操作。

2.得到Session的两种方式

得到Session有两种方式一个是方法getCurrentSession(),另一个是方法OpenSession()。

两种方法的区别是:
getCurrentSession():无论在什么地方调用,都返回同一个Session

OpenSession()重新建立一个新的Session

在一个应用程序中,如果DAO 层使用Spring 的hibernate 模板,通过Spring 来控制session 的生命周期,则首选getCurrentSession ()。
1. 如果使用的是getCurrentSession来创建session的话,在commit后,session就自动被关闭了,
也就是不用再session.close()了。但是如果使用的是openSession方法创建的session的话,
那么必须显示的关闭session,也就是调用session.close()方法。这样commit后,session并没有关闭
2.  使用SessionFactory.getCurrentSession()需要在hibernate.cfg.xml中如下配置:
* 如果是在本地,可以通过以下配置:
<property name="hibernate.current_session_context_class">thread</property>
* 如果采用了JTA事务配置如下 
<property name="hibernate.current_session_context_class">jta</property>
getcurrentSession()方法总是会返回“当前的”工作单元。
Session 在第一次被使用的时候,即第一次调用getCurrentSession()的时候,其生命周期就开始。然后她被Hibernate绑定到当前线程。当事物结束的时候,不管是提交还是回滚,Hibernate会自动把Session从当前线程剥离,并且关闭。若在次调用 getCurrentSession(),会得到一个新的Session,并且开始一个新的工作单元。这是Hibernate最广泛的thread- bound model,支持代码灵活分层(事物划分和数据访问代码的分离)。

Session在hibenate3.0以上版本,默认是JTX,通过getCurrentSession()将Session和Transaction进行绑定,Transaction无论是commit, 还是rollback都会关闭session。
通过配置,session和Thread进行绑定,Transaction无论是commit, 还是rollback都会关闭session。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值