Spring如何配置事务

Spring如何配置事务

为什么我们要配置事务,这是因为在Spring中,hibernate的事务管理是由Spring来管理的

所以我们需要配置,如果您不配置,在进行数据库写操作的时候,就会发生如下错误

org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove ‘readOnly’ marker from transaction definition.


spring配置事务也很简单,基本上也是固定的格式

第一步,配置transactionManager

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
	<property name="sessionFactory" ref="sessionFactory" />
</bean>
其中bean sessionFactory就是与数据库相关的信息,如,注入dataSource,配置数据库的连接信息等

第二步,配置事务管理的方法

也就是那些操作是由spring来管理的,写操作必须由spring来管理

<!-- 以下开始配置事务管理 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
	<tx:attributes>
		<tx:method name="update*" propagation="REQUIRED"/>
		<tx:method name="insert*" propagation="REQUIRED"/>
		<tx:method name="save*" propagation="REQUIRED"/>
		<tx:method name="delete*" propagation="REQUIRED"/>
		<tx:method name="add*" propagation="REQUIRED" />
	</tx:attributes>
</tx:advice>
以上代码表示对这些方法名进行事务管理,方法名是自定义的

第三步,开启事务,配置切入点信息

<aop:config>
	<aop:pointcut expression="(execution(* com.wyyls.shopmanager.hibernate.iter.*.*(..)))" id="userloginPC"/>
	<aop:advisor advice-ref="txAdvice" pointcut-ref="userloginPC"/>
</aop:config>
以上代码的意思就是说,对这个接口com.wyyls.shopmanager.hibernate.iter包里的所有包的,所有类的所有方法实行事务管理,按照bean txAdvice所配置的信息来管理。txAdvice里面就定义了具体的方法。




爆款云服务器s6 2核4G 低至0.46/天,具体规则查看活动详情Blog Img