码迷,mamicode.com
首页 > Web开发 > 详细

(21)项目中Hibernate Session的管理方式

时间:2016-07-20 06:49:56      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:hibernate


1、openSession和getCurrentSession的区别

package com.rk.hibernate.cache;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class App_SessionInProject
{
	private static SessionFactory sf;
	static
	{
		sf = new Configuration()
						.configure()
						.addClass(Department.class)
						.addClass(Employee.class)
						.buildSessionFactory();
	}
	
	@Test
	public void testSession()
	{
		//openSession:  创建Session, 每次都会创建一个新的session
		Session session1 = sf.openSession();
		Session session2 = sf.openSession();
		System.out.println(session1 == session2);
		session1.close();
		session2.close();

		//getCurrentSession 创建或者获取session
		// 线程的方式创建session  
		// 一定要配置:<property name="hibernate.current_session_context_class">thread</property>
		Session session3 = sf.getCurrentSession();
		Session session4 = sf.getCurrentSession();
		System.out.println(session3 == session4);
		
		// 关闭 【以线程方式创建的session,可以不用关闭; 线程结束session自动关闭】
		//session3.close();
		//session4.close(); 报错,因为同一个session已经关闭了!
	}
}


2、strut2项目中使用Hibernate Session


hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<!-- 数据库连接信息 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>	
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>	
		<property name="hibernate.connection.url">jdbc:mysql:///hib_demo</property>	
		<property name="hibernate.connection.username">root</property>	
		<property name="hibernate.connection.password">root</property>	
		<property name="hibernate.show_sql">true</property>
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!-- session创建方式 -->
		<property name="hibernate.current_session_context_class">thread</property>
		
		<!-- 加载映射 -->
		<mapping resource="com/rk/entity/Department.hbm.xml"/>
		<mapping resource="com/rk/entity/Employee.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

HibernateUtils.java

package com.rk.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtils {

	// 初始化SessionFactory
	private static SessionFactory sf;
	static {
		sf = new Configuration().configure().buildSessionFactory();
	}
	
	// 创建(获取)Session
	public static Session getSession() {
		// 线程的方式创建session,必须要配置
		// 可以不用关闭,会自动关。
		return sf.getCurrentSession();
	}
}

SessionInterceptor.java

package com.rk.interceptor;

import org.hibernate.Session;

import com.rk.utils.HibernateUtils;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * Session管理拦截器:
 * 	  当访问action的时候,创建session; 
 * 	 action ---> service  --> dao 【获取的是这里创建的session】
 * 
 *
 */
public class SessionInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		try {
			// 1. 先创建Session
			Session session = HibernateUtils.getSession();
			// 2. 开启事务
			session.beginTransaction();
			
			// 3. 执行Action
			String result = invocation.invoke();
			
			// 4. 提交事务
			session.getTransaction().commit();  // 不需要关闭session
			
			// 返回结果视图
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}

}

DepartmentDao.java

package com.rk.dao;

import com.rk.entity.Dept;
import com.rk.utils.HibernateUtils;

public class DepartmentDao {

	/**
	 * 主键查询
	 */
	public Department findById(int id){
		// 获取session, 执行操作
		return (Department) HibernateUtils.getSession().get(Department.class, id);
	}
}


3、HibernateUtil.java

package com.rk.hibernate.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil
{
	private static final SessionFactory sf;
	private static final ThreadLocal<Session> threadSession = new ThreadLocal<Session>();
	private static final ThreadLocal<Transaction> threadTransaction = new ThreadLocal<Transaction>();
	static
	{
		Configuration cfg = new Configuration();
		sf = cfg.configure().buildSessionFactory();
	}

	public static Session getSession()
	{
		Session session = threadSession.get();
		try
		{
			// Open a new Session, if this thread has none yet
			if (session == null)
			{
				session = sf.openSession();
				threadSession.set(session);
			}
		}
		catch (HibernateException e)
		{
			throw new RuntimeException(e);
		}
		return session;
	}

	public static void closeSession()
	{
		try
		{
			Session session = threadSession.get();
			threadSession.set(null);
			if (session != null && session.isOpen())
			{
				session.close();
			}
		}
		catch (HibernateException e)
		{
			throw new RuntimeException(e);
		}
	}

	public static void beginTransaction()
	{
		Transaction tx = threadTransaction.get();
		try
		{
			if (tx == null)
			{
				tx = getSession().beginTransaction();
				threadTransaction.set(tx);
			}
		}
		catch (HibernateException e)
		{
			throw new RuntimeException(e);
		}
	}

	public static void commitTransaction()
	{
		Transaction tx = threadTransaction.get();
		try
		{
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
			{
				tx.commit();
				threadTransaction.set(null);
			}
		}
		catch (HibernateException e)
		{
			rollbackTransaction();
		}
	}

	public static void rollbackTransaction()
	{
		Transaction tx = threadTransaction.get();
		try
		{
			if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
			{
				threadTransaction.set(null);
				tx.rollback();
			}
		}
		catch (HibernateException ex)
		{
			throw new RuntimeException(ex);
		}
		finally
		{
			closeSession();
		}
	}
}


过滤器

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
        throws IOException, ServletException 
{
    try 
    {
        chain.doFilter(request, response);
        HibernateUtil.commitTransaction();
    } finally {
        HibernateUtil.closeSession();
    }
}


DAO

public void execute() { 
    // Get values from request 
    try { 
        HibernateUtil.beginTransaction(); 
        Session session = HibernateUtil.getSession(); 

        // Forward to Success.jsp page 
    } catch (HibernateException ex) { 
        throw new InfrastructureException(ex); 
    } catch (Exception ex) { 
        // Throw application specific exception 
    } 
}





(21)项目中Hibernate Session的管理方式

标签:hibernate

原文地址:http://lsieun.blog.51cto.com/9210464/1827879

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!