一、引入<tx:>命名空间
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
二、具有@Transactional 注解的bean自动配置为声明式事务支持
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- 对标注@Transaction注解的Bean进行事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
三、在接口或类的声明处 ,写一个@Transactional. 要是只在接口上写, 接口的实现类就会继承下来、接口的实现类的具体方法,可以覆盖类声明处的设置
@Transactional //类级的注解、适用于类中所有的public的方法
public class TempService {
public void addTemp(){
User user = new User();
Dept dept = new Dept();
user.setRemark("USER REMARK");
dept.setRemark("DEPT REMARK");
userDAO.save(user);
deptDAO.save(dept);
}
@Transactional(readOnly=true) //提供额外的注解信息、覆盖类级的注解
public void findAll(){
userDAO.findAll();
}
注意:
1、@Transactional 只能被应用到public方法上, 对于其它非public的方法,如果标记了@Transactional也不会报错,但方法没有事务功能
2、最好在实现类上使用@Transaction注解