Spring MVC @Transactional注解方式事务失效的解决办法

 最近换了框架,新项目(Spring mvc + Spring + myBatis +  maven)送测试后,发现一个很严重的问题:@Transactional注解没生效,导致需要事务回滚的时候,事务没有回滚,最终导致数据库中的数据产生了不统一。

先展示问题:

spring-mybatis.xml配置:

	
	
	
	
		
	
	
	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	

	
	
		
		
		
	

	
	
		
		
	

	
	
		
	


spring-mvc.xml配置:


	
	
	
	
		
			
				text/html;charset=UTF-8
			
		
	
	
	
		
			
					
			
		
	
	
	
		
		
		
	
	
	
	  
        
          
        
          
        
          
     


由于web.xml中配置:


	
		contextConfigLocation
		classpath:spring-mybatis.xml
	
	
	
		encodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		true
		
			encoding
			UTF-8
		
	
	
		encodingFilter
		/*
	
	
	
		org.springframework.web.context.ContextLoaderListener
	
	
	
		org.springframework.web.util.IntrospectorCleanupListener
	

	
	
		SpringMVC
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			classpath:spring-mvc.xml
		
		1
		true
	
	
		SpringMVC
		
		/
	
	
		/index.jsp
	


Spring容器优先加载由ServletContextListener(对应spring-mybatis.xml)产生的父容器,而SpringMVC(对应spring-mvc.xml)产生的是子容器。子容器Controller进行扫描装配时装配的@Service注解的实例是没有经过事务加强处理,即没有事务处理能力的Service,而父容器进行初始化的Service是保证事务的增强处理能力的。如果不在子容器中将Service exclude掉,此时得到的将是原样的无事务处理能力的Service。

 

经过以上分析,解决方案如下

spring-mybatis.xml增加:


spring-mvc.xml增加:


 	 

 

 

参考资料:http://blog.csdn.net/z69183787/article/details/37819831

你可能感兴趣的:(ssh,java)