工作笔记-Spring5的坑:Could not obtain transaction-synchronized Session for current thread

探讨了在项目中将Hibernate和Spring升级至5版本后遇到的常见问题,特别是关于如何正确获取当前事务的session,以及在不同情况下如何避免Couldnotobtaintransaction-synchronizedSessionforcurrentthread错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目把Hibernate和Spring升级到了5,记录出现的常见问题。

想要获取当前的事务的session,在Hibernate3通过HibernateDaoSupport的getSession()方法:

	protected final Session getSession()
		throws DataAccessResourceFailureException, IllegalStateException {

		return getSession(this.hibernateTemplate.isAllowCreate());
	}

升级到Hibernate5以后,该方法被删除,可以使用currentSession()方法代替

	protected final Session currentSession() throws DataAccessResourceFailureException {
		SessionFactory sessionFactory = getSessionFactory();
		Assert.state(sessionFactory != null, "No SessionFactory set");
		return sessionFactory.getCurrentSession();
	}

替换以后,运行程序,发现报错org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread,下面贴部分错误提示。

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
	at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:137)
	at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:699)
	at org.springframework.orm.hibernate5.support.HibernateDaoSupport.currentSession(HibernateDaoSupport.java:136)

错误提示很直白了,就是当前没有事务的session,所以报错, 将代码做以下调整,可以解决:

Session session = null;
try {
	    session = currentSession();
	} catch (HibernateException he) {
		//当前没有事务不做任何处理
	}

Spring3在没有当前事务的情况下不会报错,Spring5却出现了错误?追踪下源码,发现两者的区别。

先看Spring3的处理,从HibernateDaoSupport的getSession开始追踪,最终找到org.springframework.orm.hibernate3.SessionFactoryUtils的doGetSession方法:

private static Session doGetSession(
			SessionFactory sessionFactory, Interceptor entityInterceptor,
			SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate)
			throws HibernateException, IllegalStateException {

		Assert.notNull(sessionFactory, "No SessionFactory specified");

		Object resource = TransactionSynchronizationManager.getResource(sessionFactory);
		if (resource instanceof Session) {
			return (Session) resource;
		}
		SessionHolder sessionHolder = (SessionHolder) resource;
		if (sessionHolder != null && !sessionHolder.isEmpty()) {
			// pre-bound Hibernate Session
			Session session = null;
			if (TransactionSynchronizationManager.isSynchronizationActive() &&
					sessionHolder.doesNotHoldNonDefaultSession()) {
				// Spring transaction management is active ->
				// register pre-bound Session with it for transactional flushing.
				session = sessionHolder.getValidatedSession();
				if (session != null && !sessionHolder.isSynchronizedWithTransaction()) {
					logger.debug("Registering Spring transaction synchronization for existing Hibernate Session");
					TransactionSynchronizationManager.registerSynchronization(
							new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false));
					sessionHolder.setSynchronizedWithTransaction(true);
					// Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
					// with FlushMode.MANUAL, which needs to allow flushing within the transaction.
					FlushMode flushMode = session.getFlushMode();
					if (flushMode.lessThan(FlushMode.COMMIT) &&
							!TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
						session.setFlushMode(FlushMode.AUTO);
						sessionHolder.setPreviousFlushMode(flushMode);
					}
				}
			}
			else {
				// No Spring transaction management active -> try JTA transaction synchronization.
				session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator);
			}
			if (session != null) {
				return session;
			}
		}

		logger.debug("Opening Hibernate Session");
		Session session = (entityInterceptor != null ?
				sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession());

		// Use same Session for further Hibernate actions within the transaction.
		// Thread object will get removed by synchronization at transaction completion.
		if (TransactionSynchronizationManager.isSynchronizationActive()) {
			// We're within a Spring-managed transaction, possibly from JtaTransactionManager.
			logger.debug("Registering Spring transaction synchronization for new Hibernate Session");
			SessionHolder holderToUse = sessionHolder;
			if (holderToUse == null) {
				holderToUse = new SessionHolder(session);
			}
			else {
				holderToUse.addSession(session);
			}
			if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
				session.setFlushMode(FlushMode.MANUAL);
			}
			TransactionSynchronizationManager.registerSynchronization(
					new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true));
			holderToUse.setSynchronizedWithTransaction(true);
			if (holderToUse != sessionHolder) {
				TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse);
			}
		}
		else {
			// No Spring transaction management active -> try JTA transaction synchronization.
			registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder);
		}

		// Check whether we are allowed to return the Session.
		if (!allowCreate && !isSessionTransactional(session, sessionFactory)) {
			closeSession(session);
			throw new IllegalStateException("No Hibernate Session bound to thread, " +
				"and configuration does not allow creation of non-transactional one here");
		}

		return session;
	}

提取关键代码

logger.debug("Opening Hibernate Session");
		Session session = (entityInterceptor != null ?
				sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession());

在没有获取到当前事务的session时创建一个session,所以不管当前有没有做事务(注解或显示创建),getSession()都不会报错。

再看Spring5,从HibernateDaoSupport开始跟踪currentSession()的实现,如果你的SessionFactory配置的是LocalSessionFactoryBean的工厂模式的话,会在org.hibernate.internal.SessionFactoryImpl找到CurrentSession的实现

	public Session getCurrentSession() throws HibernateException {
		if ( currentSessionContext == null ) {
			throw new HibernateException( "No CurrentSessionContext configured!" );
		}
		return currentSessionContext.currentSession();
	}

进一步追踪currentSessionContext, 找到初始化方法

		currentSessionContext = buildCurrentSessionContext();

详细代码

	private CurrentSessionContext buildCurrentSessionContext() {
		String impl = properties.getProperty( Environment.CURRENT_SESSION_CONTEXT_CLASS );
		// for backward-compatibility
		if ( impl == null ) {
			if ( canAccessTransactionManager() ) {
				impl = "jta";
			}
			else {
				return null;
			}
		}

		if ( "jta".equals( impl ) ) {
//			if ( ! transactionFactory().compatibleWithJtaSynchronization() ) {
//				LOG.autoFlushWillNotWork();
//			}
			return new JTASessionContext( this );
		}
		else if ( "thread".equals( impl ) ) {
			return new ThreadLocalSessionContext( this );
		}
		else if ( "managed".equals( impl ) ) {
			return new ManagedSessionContext( this );
		}
		else {
			try {
				Class implClass = serviceRegistry.getService( ClassLoaderService.class ).classForName( impl );
				return ( CurrentSessionContext ) implClass
						.getConstructor( new Class[] { SessionFactoryImplementor.class } )
						.newInstance( this );
			}
			catch( Throwable t ) {
				LOG.unableToConstructCurrentSessionContext( impl, t );
				return null;
			}
		}
	}

第一行代码的Environment.CURRENT_SESSION_CONTEXT_CLASS我们可以在org.springframework.orm.hibernate5.LocalSessionFactoryBuilder中找到赋值,所以我们知道实际使用的是SpringSessionContext这个类。

public LocalSessionFactoryBuilder(
			@Nullable DataSource dataSource, ResourceLoader resourceLoader, MetadataSources metadataSources) {

		super(metadataSources);

		getProperties().put(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName());
            //后略
		}

进一步追踪,会找到currentSession()在SpringSessionContext里的实现,代码比较长,分段看。

Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
		if (value instanceof Session) {
			return (Session) value;
		}
		else if (value instanceof SessionHolder) {
			SessionHolder sessionHolder = (SessionHolder) value;
			Session session = sessionHolder.getSession();
			if (!sessionHolder.isSynchronizedWithTransaction() &&
					TransactionSynchronizationManager.isSynchronizationActive()) {
				TransactionSynchronizationManager.registerSynchronization(
						new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
				sessionHolder.setSynchronizedWithTransaction(true);
				// Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
				// with FlushMode.MANUAL, which needs to allow flushing within the transaction.
				FlushMode flushMode = SessionFactoryUtils.getFlushMode(session);
				if (flushMode.equals(FlushMode.MANUAL) &&
						!TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
					session.setFlushMode(FlushMode.AUTO);
					sessionHolder.setPreviousFlushMode(flushMode);
				}
			}
			return session;
		}

第一段:从TransactionSynchronizationManager找session。

跟进getResource方法,(TransactionSynchronizationManager)

	@Nullable
	public static Object getResource(Object key) {
		Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
		Object value = doGetResource(actualKey);
		if (value != null && logger.isTraceEnabled()) {
			logger.trace("Retrieved value [" + value + "] for key [" + actualKey + "] bound to thread [" +
					Thread.currentThread().getName() + "]");
		}
		return value;
	}

继续跟进,doGetResource方法,(TransactionSynchronizationManager)

	private static Object doGetResource(Object actualKey) {
		Map<Object, Object> map = resources.get();
		if (map == null) {
			return null;
		}
		Object value = map.get(actualKey);
		// Transparently remove ResourceHolder that was marked as void...
		if (value instanceof ResourceHolder && ((ResourceHolder) value).isVoid()) {
			map.remove(actualKey);
			// Remove entire ThreadLocal if empty...
			if (map.isEmpty()) {
				resources.remove();
			}
			value = null;
		}
		return value;
	}

resources.get()返回的一个map,回头看resource的声明

private static final ThreadLocal<Map<Object, Object>> resources =
			new NamedThreadLocal<>("Transactional resources");

resources是一个ThreadLocal线程变量,在TransactionSynchronizationManager中有对其进行添加绑定的方法:

public static void bindResource(Object key, Object value) throws IllegalStateException {
		Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
		Assert.notNull(value, "Value must not be null");
		Map<Object, Object> map = resources.get();
		// set ThreadLocal Map if none found
		if (map == null) {
			map = new HashMap<>();
			resources.set(map);
		}
		Object oldValue = map.put(actualKey, value);
		// Transparently suppress a ResourceHolder that was marked as void...
		if (oldValue instanceof ResourceHolder && ((ResourceHolder) oldValue).isVoid()) {
			oldValue = null;
		}
		if (oldValue != null) {
			throw new IllegalStateException("Already value [" + oldValue + "] for key [" +
					actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]");
		}
		if (logger.isTraceEnabled()) {
			logger.trace("Bound value [" + value + "] for key [" + actualKey + "] to thread [" +
					Thread.currentThread().getName() + "]");
		}
	}

通过实验发现,在方法有@Transational注解的情况下,getResource返回的value是一个sessionHolder,在没有注解的情况下返回的value是null。既而想到,注解的实现过程,调用了bindResource方法。

我们知道Spring注解基本都是基于AOP实现的,spring-tx是对事务支持的包,在里面找到了TransactionAspectSupport,里面有这样一个方法

@Nullable
	protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
			final InvocationCallback invocation) throws Throwable {

		// If the transaction attribute is null, the method is non-transactional.
		TransactionAttributeSource tas = getTransactionAttributeSource();
		final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
		final PlatformTransactionManager tm = determineTransactionManager(txAttr);
		final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

		if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
			// Standard transaction demarcation with getTransaction and commit/rollback calls.
			TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
			Object retVal = null;
			try {
				// This is an around advice: Invoke the next interceptor in the chain.
				// This will normally result in a target object being invoked.
				retVal = invocation.proceedWithInvocation();
			}
			catch (Throwable ex) {
				// target invocation exception
				completeTransactionAfterThrowing(txInfo, ex);
				throw ex;
			}
			finally {
				cleanupTransactionInfo(txInfo);
			}
			commitTransactionAfterReturning(txInfo);
			return retVal;
		}


//后略

在所有添加@Transaction注解的方法执行前,都会调用此方法,里面有个关键的调用createTransactionIfNecessary。跟进去

	protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm,
			@Nullable TransactionAttribute txAttr, final String joinpointIdentification) {

		// If no name specified, apply method identification as transaction name.
		if (txAttr != null && txAttr.getName() == null) {
			txAttr = new DelegatingTransactionAttribute(txAttr) {
				@Override
				public String getName() {
					return joinpointIdentification;
				}
			};
		}

		TransactionStatus status = null;
		if (txAttr != null) {
			if (tm != null) {
				status = tm.getTransaction(txAttr);
			}
			else {
				if (logger.isDebugEnabled()) {
					logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
							"] because no transaction manager has been configured");
				}
			}
		}
		return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
	}

tm就是我们配置的HibernateTransactionManager,这里不会是null,继续进入,找到org.springframework.transaction.support.AbstractPlatformTransactionManager的getTransaction方法

	public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException {
		Object transaction = doGetTransaction();

		// Cache debug flag to avoid repeated checks.
		boolean debugEnabled = logger.isDebugEnabled();

		if (definition == null) {
			// Use defaults if no transaction definition given.
			definition = new DefaultTransactionDefinition();
		}

		if (isExistingTransaction(transaction)) {
			// Existing transaction found -> check propagation behavior to find out how to behave.
			return handleExistingTransaction(definition, transaction, debugEnabled);
		}

		// Check definition settings for new transaction.
		if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
			throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
		}

		// No existing transaction found -> check propagation behavior to find out how to proceed.
		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
			throw new IllegalTransactionStateException(
					"No existing transaction found for transaction marked with propagation 'mandatory'");
		}
		else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
				definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
				definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
			SuspendedResourcesHolder suspendedResources = suspend(null);
			if (debugEnabled) {
				logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
			}
			try {
				boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
				DefaultTransactionStatus status = newTransactionStatus(
						definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
				doBegin(transaction, definition);
				prepareSynchronization(status, definition);
				return status;
			}
			catch (RuntimeException | Error ex) {
				resume(null, suspendedResources);
				throw ex;
			}
		}
		else {
			// Create "empty" transaction: no actual transaction, but potentially synchronization.
			if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
				logger.warn("Custom isolation level specified but no actual transaction initiated; " +
						"isolation level will effectively be ignored: " + definition);
			}
			boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
			return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
		}
	}

Propagation声明为PROPAGATION_REQUIRED(默认)、PROPAGATION_REQUIRES_NEW、PROPAGATION_NESTED的事务会进入else if 分支,进入doBegin,该方法的实现在org.springframework.transaction.support.HibernateTransactionManager

	protected void doBegin(Object transaction, TransactionDefinition definition) {
		HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

		//略
		Session session = null;

		try {
			//前略

			// Bind the session holder to the thread.
			if (txObject.isNewSessionHolder()) {
				TransactionSynchronizationManager.bindResource(obtainSessionFactory(), txObject.getSessionHolder());
			}
			txObject.getSessionHolder().setSynchronizedWithTransaction(true);
		}

		catch (Throwable ex) {
			//略
		}
	}

最终进行了bindResource操作。所以回到最开始的CurrentSession()的代码。

Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);这一行,将获得sessionHolder, 然后返回session。

所以在没有注解的情况下,没有bindResource操作,value的值将是null,进入到下一个判断分支:

if (this.transactionManager != null && this.jtaSessionContext != null) {
			try {
				if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) {
					Session session = this.jtaSessionContext.currentSession();
					if (TransactionSynchronizationManager.isSynchronizationActive()) {
						TransactionSynchronizationManager.registerSynchronization(
								new SpringFlushSynchronization(session));
					}
					return session;
				}
			}
			catch (SystemException ex) {
				throw new HibernateException("JTA TransactionManager found but status check failed", ex);
			}
		}

在this.transactionManager和this.jtaSessionContext都非空的情况下,进入这个分支。找到这两个成员变量的赋值代码:

	public SpringSessionContext(SessionFactoryImplementor sessionFactory) {
		this.sessionFactory = sessionFactory;
		try {
			JtaPlatform jtaPlatform = sessionFactory.getServiceRegistry().getService(JtaPlatform.class);
			this.transactionManager = jtaPlatform.retrieveTransactionManager();
			if (this.transactionManager != null) {
				this.jtaSessionContext = new SpringJtaSessionContext(sessionFactory);
			}
		}
		catch (Exception ex) {
			LogFactory.getLog(SpringSessionContext.class).warn(
					"Could not introspect Hibernate JtaPlatform for SpringJtaSessionContext", ex);
		}
	}

观察这一行JtaPlatform jtaPlatform = sessionFactory.getServiceRegistry().getService(JtaPlatform.class);

sessionFactory是我们的LocalSessionFactoryBean工厂类创建的SessionFactoryImpl,如果项目没有使用JTA的事务管理,所以这里jtaPlatform返回的是NoJtaPlatForm;retrieveTransactionManager()返回的是Null, 最终初始化以后jtaSessionContext为null。 

所以也进入不了CurrentSession()的第二个if分支。

进入下一个分支的判断:

if (TransactionSynchronizationManager.isSynchronizationActive()) {
			Session session = this.sessionFactory.openSession();
			if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
				session.setFlushMode(FlushMode.MANUAL);
			}
			SessionHolder sessionHolder = new SessionHolder(session);
			TransactionSynchronizationManager.registerSynchronization(
					new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true));
			TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder);
			sessionHolder.setSynchronizedWithTransaction(true);
			return session;
		}

进入TransactionSynchronizationManager.isSynchronizationActive()方法

	public static boolean isSynchronizationActive() {
		return (synchronizations.get() != null);
	}

如果threadLocal变量synchronizations有内容,才会返回true。看synchronizations的定义

	private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations =
			new NamedThreadLocal<>("Transaction synchronizations");

TransactionSynchronizationManager.isSynchronizationActive()返回true说明当前已经处于事务当中,可以继续处理生成嵌套事务。

最后三个分支都没有进入的话:

		else {
			throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
		}

出现报错。

 

有错误的地方请指教,拜托了!

<think>好的,我现在要解决用户遇到的Hibernate异常:“org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread”。首先,我需要理解这个问题的根本原因。根据用户提供的引用,特别是引用[4]提到,这个问题通常是因为跨过Service层直接调用Dao层导致的,因为事务通常是在Service层管理的[^4]。另外,引用[2]指出,当无法获取到事务同步的Session时,Hibernate会抛出这个异常[^2]。 接下来,我需要考虑可能的解决方案。根据引用[5],配置事务注解驱动可能是一个解决方法,比如在Spring配置文件中添加`<tx:annotation-driven transaction-manager="transactionManager"/>`[^5]。此外,引用[3]中的示例代码显示,直接使用openSession()而不是getCurrentSession()可能会绕过这个问题,但这样做可能需要手动管理事务,不够理想[^3]。 首先,应该检查是否在Service层正确配置了事务管理。确保Service方法上使用了@Transactional注解,这样Spring才能代理事务。然后,Dao层应该通过getCurrentSession()来获取Session,而不是openSession(),因为后者不会与事务绑定。 另外,检查Spring的配置文件是否正确配置了事务管理器和注解驱动。例如,是否声明了PlatformTransactionManager,以及是否启用了注解驱动的事务管理。 还需要确认Hibernate的版本是否与Spring版本兼容,特别是Hibernate 4及以上版本可能存在配置差异。如果配置正确,但仍然存在问题,可能需要调整SessionFactory的配置,确保它与Spring的事务管理正确集成。 总结可能的解决步骤: 1. 确保Service层使用@Transactional注解。 2. 检查Dao层是否使用getCurrentSession()而非其他方式获取Session。 3. 验证Spring配置中的事务管理器和注解驱动是否正确设置。 4. 避免在Dao层直接调用非事务方法。 同时,用户提供的引用[3]中提到的直接使用openSession()并手动管理事务虽然可行,但不符合最佳实践,可能导致事务管理混乱,应优先使用Spring声明式事务管理。</think>### 解决方案:Hibernate无法获取事务同步Session的排查与修复 #### 问题原因分析 该异常通常由以下原因导致: 1. **未正确配置事务管理**:Service层未启用事务管理,导致Dao层无法通过`getCurrentSession()`获取与事务绑定的Session。 2. **直接调用Dao层**:跨过Service层直接调用Dao层方法,绕过了事务代理机制。 3. **错误使用Session获取方式**:在Dao层使用`openSession()`而非`getCurrentSession()`,导致Session未与事务绑定。 --- #### 分步解决方案 ##### 1. 确保Service层启用事务管理 - **添加@Transactional注解**:在Service类或方法上添加Spring事务注解,声明事务边界。 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Transactional // 关键注解,启用事务管理 @Override public void updateUser(User user) { userDao.update(user); } } ``` ##### 2. 检查Dao层Session获取方式 - **使用`getCurrentSession()`**:Dao层必须通过`sessionFactory.getCurrentSession()`获取Session,确保Session与事务绑定。 ```java @Repository public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; // 正确方式:获取事务同步的Session private Session getSession() { return sessionFactory.getCurrentSession(); } @Override public void update(User user) { getSession().update(user); // 无需手动提交事务 } } ``` ##### 3. 验证Spring事务配置 - **配置事务管理器与注解驱动**:在Spring配置文件中(如`applicationContext.xml`)添加以下内容: ```xml <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 启用注解驱动的事务管理 --> <tx:annotation-driven transaction-manager="transactionManager"/> ``` ##### 4. 避免跨层调用 - **通过Service层调用Dao**:确保所有数据库操作经过Service层,禁止Controller直接调用Dao。 --- #### 其他注意事项 - **HibernateSpring版本兼容性**:Hibernate 4+需使用`HibernateTransactionManager`,而非旧版`Hibernate3TransactionManager`。 - **事务传播行为**:若需嵌套事务,可通过`@Transactional(propagation = Propagation.REQUIRED)`指定传播机制。 - **手动回滚事务**:在事务方法中捕获异常后,可调用`TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()`手动回滚。 --- ### 相关问题 1. **如何在Spring中配置声明式事务管理?** 2. **@Transactional注解有哪些常用属性?** 3. **Hibernate的`getCurrentSession()`和`openSession()`有什么区别?** 4. **事务传播机制有哪些类型?如何选择?**
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值