第一步,在Spring的配置文件中,修改配置信息
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
第二步,在Spring的配置文件中配置bean
<!-- 如果在一个类前面加上了@Transactional那么该类在执行每一个方法之前开启一个事务,方法结束后关闭一个事务 -->
<!--
如果是Runtime Exception(一般叫unchecked)那么事务会回滚
;Exception这种异常事务是不会回滚的,一般叫checked
(如果想在这种异常上发生回滚,那么可以在方法前加上@Transaction(roallBack=Exception.class))
-->
<!--
事务对性能有影响,如果某个方法不需要事务,那么可以在他的前面加上@Transactional(propagation=Propagation.NOT_SUPPORTED)
-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" /><!--开启注解-->
第三步,在业务逻辑层的接口中注解需要管理的类
package cn.edu.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import cn.edu.model.Users;
@Transactional
public interface UsersManagerDao {
public void save(Users user);
public void delete(Users user);
@Transactional(readOnly=true)
public Users findById(Integer id);
public List<Users> findAll();
}
那么,在调用其中方法的时候,会在一个方法的开始开启事务,在方法的结束提交事务。