Hibernate Session

Hibernate在对资料库进行操作之前,必须先取得Session实例,Session是hibernate数据库操作的基础,它不是我们所说的JSP页面传递参数的Session。Session是Hibernate运作的中心,对象的生命周期、事务的管理、数据库的存取都与session息息相关。

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

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



方式一:

当在Myeclipse引入Myeclipse自带的Hibernate框架后,Myeclipse会自动为项目创建一个HibernateSessionFactory类,源码如下:

package com.yao.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;
	}

}


测试类:

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("yao");
			user.setUserpass("123456");
			session.save(user);
			System.out.println("数据成功写入....");
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
			session.close();
		}

	}

这里的session通过HiberinateSeesionFactory得到。


方式二:

直接在类中读取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("yao");
		user.setUserpass("123456");
		session.save(user);
		tx.commit();
	}


从xml文件读取配置信息构建SessionFactory步骤如下:

1 )创建一个Configuration对象,并通过该对象的configura()方法加载Hibernate配置文件,代码如下。   
Configuration config =  new  Configuration().configure();   
configura()方法:用于告诉Hibernate加载hibernate.cfg.xml文件。Configuration在实例化时默认加载classpath中的hibernate.cfg.xml,当然也可以加载名称不是hibernate.cfg.xml的配置文件,例如wghhibernate.cfg.xml,可以通过以下代码实现。   
Configuration config =  new  Configuration().configure( "wghhibernate.cfg.xml" );   

2)完成配置文件和映射文件的加载后,将得到一个包括所有Hibernate运行期参数的Configuration实例,通过Configuration实例buildSessionFactory()方法可以构建一个惟一的SessionFactory,代码如下:  

SessionFactory sessionFactory = config.buildSessionFactory();   

构建SessionFactory要放在静态代码块中,因为它只在该类被加载时执行一次。   

猜你喜欢

转载自blog.csdn.net/xia236326/article/details/73742452