使用基于@Transactional的Spring配置
<beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="entityManagerFactory" ref="entityManagerFactory" />
</beans:bean>
<!-- 声明使用注解式事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
直接在需要事务的类或者方法上使用@Transactional就可以标记该类或者该方法使用事务管理数据库操作
注意加载顺序,spring-mybatis和spring-mvc加载的顺序,在配置文件中的顺序如下
spring-mvc.xml文件,不加载controller文件
<!-- 自动扫描组件,这里要把controler下面的 controller去除,他们是在spring3-servlet.xml中配置的,如果不去除会影响事务管理的。 -->
<context:component-scan base-package="com.sence">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
spring-mybatis.xml文件,不加载service
<!-- 扫描所有的controller 但是不扫描service-->
<context:component-scan base-package="com.sence">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
@Transactional管理事务
最新推荐文章于 2023-08-22 23:13:40 发布