您的位置:首页 > 其它

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

2016-07-19 20:48 274 查看
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
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate