Spring事务管理:编程式和声明式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fly910905/article/details/83507040

Spring的事务管理:

Spring的事务管理分成两类:

* 编程式事务管理:

-------手动编写代码完成事务管理.

* 声明式事务管理:

-------不需要手动编写代码,配置.

事务操作的环境搭建:

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `money` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `account` VALUES ('1', 'aaa', '1000');
INSERT INTO `account` VALUES ('2', 'bbb', '1000');
INSERT INTO `account` VALUES ('3', 'ccc', '1000');

 

创建一个web项目:

* 导入相应jar包

* 引入配置文件:

* applicationContext.xml、log4j.properties、jdbc.properties

 

创建类:

* AccountService

* AccountDao

 

在Spring中注册:

<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 引入外部属性文件. -->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!-- 配置c3p0连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

<!-- 业务层类 -->
<bean id="accountService" class="cn.itcast.spring3.demo1.AccountServiceImpl">
<!-- 在业务层注入Dao -->
<property name="accountDao" ref="accountDao"/>
<!-- 在业务层注入事务的管理模板 -->
<property name="transactionTemplate" ref="transactionTemplate"/>
</bean>

<!-- 持久层类 -->
<bean id="accountDao" class="cn.itcast.spring3.demo1.AccountDaoImpl">
<!-- 注入连接池的对象,通过连接池对象创建模板. -->
<property name="dataSource" ref="dataSource"/>
</bean>

<!-- 事务管理的模板 -->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"/>
</bean>

<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 需要注入连接池,通过连接池获得连接 -->
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>

Spring事务管理示例:银行转账

猜你喜欢

转载自blog.csdn.net/fly910905/article/details/83507040
今日推荐