Spring之事务的三种实现方式

本文深入探讨了Spring框架中三种不同的事务管理方式:声明式事务、注解式事务和编码式事务,通过具体代码实例展示了每种方式的配置与实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建表tb_test

CREATE TABLE `tb_test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `context` varchar(255) NOT NULL COMMENT '没有实际含义',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

定义pojo

public class TbTest {
    private Integer id;

    private String context;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }
}

定义dao和daoImpl

public interface TbTestDao extends EntityDao<TbTest,Integer> {

}
public class TbTestDaoImpl extends EntityDaoImpl<TbTest,Integer> implements TbTestDao {

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }
}

1.声明式事务---使用tx:advice标签元素实现事务

TbTestService.java

public interface TbTestService {
    void save(String context) throws Exception;
}

TbTestServiceImpl.java

public class TbTestServiceImpl implements TbTestService{

    private TbTestDao tbTestDao;

    public void setTbTestDao(TbTestDao tbTestDao) {
        this.tbTestDao = tbTestDao;
    }

    @Override
    public void save(String context) throws Exception {
        tbTestDao.insertWithSql(new SQL().insert("id","context").values(null,context));
        throw new RuntimeException("gun");
    }
}

txAdviceTranscation.xml

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

    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 数据库基本信息配置 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;zeroDateTimeBehavior=convertToNull&amp;autoReconnect=true"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="initialSize" value="1"/>
        <property name="maxActive" value="300"/>
        <property name="maxIdle" value="2"/>
        <property name="minIdle" value="1"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="druidDataSource"/>
    </bean>

    <bean id="tbTestDao" class="org.springframework.study.day16.dao.TbTestDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="tbTestService" class="org.springframework.study.day16.service.TbTestServiceImpl">
        <property name="tbTestDao" ref="tbTestDao"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"/>
    </bean>

    <!--定义事务增强点-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="txPointcut" expression="execution(* org.springframework.study.day16.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

</beans>

定义测试方法

@Test
    public void testTxAdviceTransaction() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("txAdviceTranscation.xml");
        TbTestService tbTestService = ac.getBean(TbTestService.class);
        tbTestService.save("哈喽哈喽");
    }

2.声明式事务---使用注解@Transactional方式实现事务

TbTestService.java

@Transactional(propagation = Propagation.REQUIRED)
public interface TbTestService {
    void insert(String context)throws Exception;
}

TbTestServiceImpl.java

public class TbTestServiceImpl implements TbTestService{

    private TbTestDao tbTestDao;

    public void setTbTestDao(TbTestDao tbTestDao) {
        this.tbTestDao = tbTestDao;
    }

    @Override
    public void insert(String context) throws Exception {
        tbTestDao.insertWithSql(new SQL().insert("id","context").values(null,context));
        throw new RuntimeException("干");
    }
}

annotationTranscation.xml

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

    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 数据库基本信息配置 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;zeroDateTimeBehavior=convertToNull&amp;autoReconnect=true"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="initialSize" value="1"/>
        <property name="maxActive" value="300"/>
        <property name="maxIdle" value="2"/>
        <property name="minIdle" value="1"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="druidDataSource"/>
    </bean>

    <bean id="tbTestDao" class="org.springframework.study.day16.dao.TbTestDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="tbTestService" class="org.springframework.study.day16.service.TbTestServiceImpl">
        <property name="tbTestDao" ref="tbTestDao"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"/>
    </bean>

    <!--开启tx注解-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

定义测试方法

@Test
    public void testAnnotationTransaction() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("annotationTranscation.xml");
        TbTestService tbTestService = ac.getBean(TbTestService.class);
        tbTestService.insert("嗨喽嗨");
    }

3.编码式事务---使用TransactionTemplate

TbTestService.java

public interface TbTestService {
    void create(String context) throws Exception;
}

TbTestServiceImpl.java

public class TbTestServiceImpl implements TbTestService {

    private TbTestDao tbTestDao;

    private TransactionTemplate transactionTemplate;

    public void setTbTestDao(TbTestDao tbTestDao) {
        this.tbTestDao = tbTestDao;
    }

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    @Override
    public void create(final String context) throws Exception {
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {

                try {
                    tbTestDao.insertWithSql(new SQL().insert("id", "context").values(null, context));
                    System.out.println(1/0);
                    return null;
                } catch (Exception e) {
                    status.setRollbackOnly();
                    return null;
                }
            }
        });
    }
}

transactionTemplateTest.xml

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

    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 数据库基本信息配置 -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url"
                  value="jdbc:mysql://localhost:3306/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8&amp;zeroDateTimeBehavior=convertToNull&amp;autoReconnect=true"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="initialSize" value="1"/>
        <property name="maxActive" value="300"/>
        <property name="maxIdle" value="2"/>
        <property name="minIdle" value="1"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="druidDataSource"/>
    </bean>

    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"/>
    </bean>


    <bean id="tbTestDao" class="org.springframework.study.day16.dao.TbTestDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="tbTestService" class="org.springframework.study.day16.service.TbTestServiceImpl">
        <property name="tbTestDao" ref="tbTestDao"/>
        <property name="transactionTemplate" ref="transactionTemplate"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"/>
    </bean>

</beans>

定义测试方法

@Test
    public void testTransactionTemplate() throws Exception {
        ApplicationContext ac = new ClassPathXmlApplicationContext("transactionTemplateTest.xml");
        TbTestService tbTestService = ac.getBean(TbTestService.class);
        tbTestService.create("meow");
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值