---
title: "在 Spring 中自己管理 Hibernate 事务"
author: "as619864232"
date: "2012-06-30T14:51:17Z"
tags: ["Hibernate", "Spring", "事务"]
categories: ["企业架构"]
slug: "spring-hibernate"
draft: false
lastmod: "2012-06-30T15:19:39Z"
id: 1571548
url: "https://ears.iteye.com/blog/1571548"
---

在spring中自己控制事物，并且使用 aop 拦截事务，如果需要使用得到当前session，则需要在 hibernate 的 xml 配置文件中添加属性：

hibernate 版本若为 3.x.x

hibernate.current\_thread\_class=org.hibernate.context.ThreadLocalSessionContext|thread

hibernate 版本若为 4.x.x

hibernate.current\_thread\_class=org.hibernate.context.interl.ThreadLocalSessionContext|thread

 

aop 的配置：

 

```
<bean id="muser_inter" class="org.aops.MuserAdvice">
	<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<aop:config>
	<aop:pointcut expression="execution(* org.services.impl.MuserServiceImpl.login(String, String))" id="login_pointCut" />
	<aop:advisor advice-ref="muser_inter" pointcut-ref="login_pointCut" />
</aop:config>
```

Java 代码：

 

```
package org.aops;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.hibernate.SessionFactory;

public class MuserAdvice implements MethodInterceptor {

	private SessionFactory sessionFactory;

	@Override
	public Object invoke(MethodInvocation arg0) throws Throwable {
		System.out.println("in");
		sessionFactory.getCurrentSession().beginTransaction();
		Object obj = arg0.proceed();
		System.out.println("out");
		sessionFactory.getCurrentSession().getTransaction().commit();
		return obj;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
```

 

控制台输出：

 

in

Hibernate: 

    select

        muser0\_.MUID as MUID1\_,

        muser0\_.MUNAME as MUNAME1\_,

        muser0\_.MUPWD as MUPWD1_ 

    from

        TEST.MUSER muser0_ 

    where

        muser0\_.MUNAME=? 

        and muser0\_.MUPWD=?

out