使用注解实现事务处理

添加tx和context

<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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

1,首先,将action,service,dao所有层的所有类整到容器里面;

在Dao上 @Respository("employeeDao"),去掉继承HibernateDaoSupport

    添加private HibernateTemplate hibernateTemplate;然后添加set、get方法、并且添加自动装配(@Autowired)

在Service上@Service("claimVoucherService"),添加事务@Transactional、、、Qualifier(取得资格的人)

@Repository("employeeDao")
public class EmployeeDaoHibImpl implements
        EmployeeDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;
@Transactional
@Service("claimVoucherService")
public class ClaimVoucherServiceImpl implements ClaimVoucherService {
    //记录日志
    private final Log logger = LogFactory.getLog(getClass());
    
    @Autowired
    @Qualifier("claimVoucherDao")
    private ClaimVoucherDao claimVoucherDao;

    @Autowired
    @Qualifier("claimVoucherDetailDao")
    private ClaimVoucherDetailDao claimVoucherDetailDao;    
<bean id="hibernateTemplate"
        class="org.springframework.orm.hibernate3.HibernateTemplate" autowire="byName"/>
<!-- 扫描dao和sevice包中注解标注的类 -->
    <context:component-scan 
        base-package="cn.bdqn.jboa.dao.hibimpl, cn.bdqn.jboa.service.impl" />
    
    <!-- 定义事务管理器 -->
    <bean id="txManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="txManager" />

同时会发现,如果在save,update,delete上没有加事务限制,就会报错;因为默认是只读的事务;
如果一个方法上有@Transactional这个类就创建代理对象,有了事务;
但是如果全部没有加@Transactional,就不会创建代理对象;就不存在事务;
就是只要有一个加有事务,就会创建代理对象;否则不会;是只读事务;
----
什么情况适合注解,什么情况适合配置文件?
基本类型不适合用注解,只需要赋值,框架内部分额不适合用注解;其他都可以使用注解配置实现引用;

原文地址:https://www.cnblogs.com/xuerong/p/4934997.html