spring随笔(事务配置)

本文介绍Spring框架如何简化JDBC操作,并通过不同方式管理事务,包括代码式、声明式及AOP自动管理等,实现转账功能作为示例。

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

spring中的jdbc

spring中的jdbc与传统的jdbc有什么区别?Spring的jdbc:节省代码,不管连接(Connection),不管事务、不管异常、不管关闭(con.close() ps.close )由JdbcTemplate实现crud

spring代码式管理事务

流程:
1.在xml中配置数据源(连接池)dataSource
2.配置事务管理器,注入数据源 DataSourceTransactionManager
3.配置事务管理模板transactionTemplate,注入事务管理器
4.配置JDBC模板JdbcTemplate,注入dao
5.配置service,注入dao和transactionTemplate
(如果我们使xxDao继承JdbcDaoSupport 他会在底层为我们直接new一个JdbcTemplate 无需注入,直接向注入数据源)

<?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: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.xsd
         http://www.springframework.org/schema/aop 
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 1.创建链接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl"
            value="jdbc:mysql://localhost:3306/springdemo?useUnicode=true&amp;characterEncoding=UTF8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="admin"></property>

    </bean>
    <!-- 2.配置事务管理器 事务需要从Connection 中获得,链接从连接池中获取 -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 3.创建事务管理模板 -->
    <bean id="transactionTemplate"
        class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="txManager"></property>
    </bean>
    <bean id="accountDao" class="com.spring.transaction.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean id="AccountService" class="com.spring.transaction.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
        <property name="transactionTemplate" ref="transactionTemplate"></property>
    </bean>


</beans>
package com.spring.transaction;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    @Override
    public void AccountIn(String inname, int money) {
        String sql = "update account set money=money+? where username=? ";
        this.getJdbcTemplate().update(sql, money, inname);
    }

    @Override
    public void AccountOut(String outname, int money) {
        String sql = "update account set money=money-? where username=? ";
        this.getJdbcTemplate().update(sql, money, outname);
    }

}
package com.spring.transaction;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    private TransactionTemplate transactionTemplate;

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

    // 注入
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
   //没有返回值类型 使用TransactionCallbackWithoutResult()  如果有TransactionCallback
    @Override
    public void AccountIn(String inname, String outname, int money) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                accountDao.AccountIn(inname, money);

                accountDao.AccountOut(outname, money);

            }
        });

    }

}

声明式事务管理

半自动

半自动事务流程:
1.在xml中配置数据源(连接池)dataSource
2.配置事务管理器,注入数据源 DataSourceTransactionManager
3.配置JDBC模板JdbcTemplate,注入dao
4.配置service,注入dao
5.配置TransactionProxyFactoryBean生成代理对象

<?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: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.xsd
         http://www.springframework.org/schema/aop 
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 1创建链接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl"
            value="jdbc:mysql://localhost:3306/springdemo?useUnicode=true&amp;characterEncoding=UTF8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="admin"></property>
    </bean>
    <!-- 2配置事务管理器 事务需要从Connection 中获得,链接从连接池中获取 -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <bean id="accountService" class="com.spring.semiauto_transaction.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <bean id="accountDao" class="com.spring.semiauto_transaction.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 工厂bean代理 -->
    <!-- 
    proxyInterfaces         代理对象的接口
    target                  目标类
    transactionManager      事务管理器
    transactionAttributes   事务属性 
       prop.key             确定哪些方法使用当前事务配置  
       prop.text            用于配置事务详情    
                                格式:PROPAGATION,ISOLATION,readOnly,-Exception,+Exception
                    传播行为        隔离级别    是否只读        异常回滚        异常提交            
     -->
    <bean id="proxyService"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="proxyInterfaces"
            value="com.spring.semiauto_transaction.AccountService"></property>
        <property name="target" ref="accountService"></property>
        <property name="transactionManager" ref="txManager"></property>
        <property name="transactionAttributes">
            <props>
                <prop key="AccountIn">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop>
            </props>
        </property>
    </bean>






</beans>
package com.spring.semiauto_transaction;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;

    // 注入
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }


    @Override
    public void AccountIn(String inname, String outname, int money) {
        accountDao.AccountIn(inname, money);
        //int x=1/0;
        accountDao.AccountOut(outname, money);

    }

}

基于aop自动管理

自动事务流程:
1.在xml中配置数据源(连接池)dataSource
2.配置事务管理器,注入数据源 DataSourceTransactionManager
3.配置JDBC模板JdbcTemplate,注入dao
4.配置service,注入dao
5.配置事务详情 TransactionDefintion 标签
6.aop编程

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

    <!-- 创建链接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl"
            value="jdbc:mysql://localhost:3306/springdemo?useUnicode=true&amp;characterEncoding=UTF8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="admin"></property>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 事务详情 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
    <tx:attributes>
    <tx:method name="AccountIn" isolation="DEFAULT" propagation="REQUIRED"/>
    </tx:attributes>
    </tx:advice>
    <!-- aop编程 -->
    <aop:config>
    <aop:pointcut expression="execution(* com.spring.auto_transaction..*.*(..))" id="myPointcut"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/>
    </aop:config>

    <bean id="accountService" class="com.spring.auto_transaction.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>

    </bean>
    <bean id="accountDao" class="com.spring.auto_transaction.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

注解配置

package com.spring.transaction_anno;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@Service("AccountService")
@Transactional(isolation=Isolation.DEFAULT,propagation= Propagation.REQUIRED)
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    private TransactionTemplate transactionTemplate;

    @Autowired
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }
    // 注入
    @Autowired
    @Qualifier("accountDao")
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public void AccountIn(String inname, String outname, int money) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                accountDao.AccountIn(inname, money);
                // int x=1/0;
                accountDao.AccountOut(outname, money);

            }
        });

    }

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

    <!-- 创建链接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl"
            value="jdbc:mysql://localhost:3306/springdemo?useUnicode=true&amp;characterEncoding=UTF8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="admin"></property>
    </bean>
    <!-- 配置事务管理器 事务需要从Connection 中获得,链接从连接池中获取 -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="accountDao" class="com.spring.transaction_anno.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 组件扫描 -->

    <context:component-scan base-package="com.spring.transaction_anno"></context:component-scan>
    <!-- 将管理器交予spring 
        * transaction-manager 配置事务管理器
        * proxy-target-class
        true : 底层强制使用cglib 代理 -->

    <tx:annotation-driven transaction-manager="txManager" />
</beans>
内容概要:本文《2025年全球AI Coding市场洞察研究报告》由亿欧智库发布,深入分析了AI编程工具的市场现状和发展趋势。报告指出,AI编程工具在2024年进入爆发式增长阶段,成为软件开发领域的重要趋势。AI编程工具不仅简化了代码生成、调试到项目构建等环节,还推动编程方式从人工编码向“人机协同”模式转变。报告详细评估了主流AI编程工具的表现,探讨了其商业模式、市场潜力及未来发展方向。特别提到AI Agent技术的发展,使得AI编程工具从辅助型向自主型跃迁,提升了任务执行的智能化和全面性。报告还分析了AI编程工具在不同行业和用户群体中的应用,强调了其在提高开发效率、减少重复工作和错误修复方面的显著效果。最后,报告预测2025年AI编程工具将在精准化和垂直化上进一步深化,推动软件开发行业进入“人机共融”的新阶段。 适合人群:具备一定编程基础,尤其是对AI编程工具有兴趣的研发人员、企业开发团队及非技术人员。 使用场景及目标:①了解AI编程工具的市场现状和发展趋势;②评估主流AI编程工具的性能和应用场景;③探索AI编程工具在不同行业中的具体应用,如互联网、金融、游戏等;④掌握AI编程工具的商业模式和盈利空间,为企业决策提供参考。 其他说明:报告基于亿欧智库的专业研究和市场调研,提供了详尽的数据支持和前瞻性洞察。报告不仅适用于技术从业者,也适合企业管理者和政策制定者,帮助他们在技术和商业决策中更好地理解AI编程工具的价值和潜力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值