Spring注解声明式事务配置

一、引入<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注解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值