spring_事务管理 TransactionManager

12 篇文章 0 订阅

1.spring中的TransactionManager接口

DateSourceTransactionManager 用于JDBC的事务管理

HibernateTransactionManager用于Hibernate的事务管理

JpaTransactionManager 用于Jpa的事物管理

2.spring中TransactionManager接口的定义(源码)

事务的属性介绍:这里定义了传播行为、隔离级别、超时时间、是否只读

3.转账案例

(1)项目结构

(2)导入jar

(3)建立数据库测试数据

CREATE DATABASE springjdbc
USE springjdbc
CREATE TABLE `ar_account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `money` double(255,0) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of ar_account
-- ----------------------------
INSERT INTO `ar_account` VALUES ('1', '张三', '60');
INSERT INTO `ar_account` VALUES ('2', '李四', '40');

(4)建立日志配置(log4j.properties)

# Global logging configuration
log4j.rootLogger=info, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

(5)建立数据库配置(db.properties)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springjdbc
jdbc.username=root
jdbc.password=root

(6)建立接口 AccountDao类与实现AccountDaoImpl类

package com.linxin.spring.dao;

public interface AccountDao {
	//加钱
	void addMoney(Integer id,Double money);
	//减钱
	void subMoney(Integer id,Double money);

}
package com.linxin.spring.dao;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
	@Resource(name="jdbctemplate")
	private JdbcTemplate jt;
	
	@Override
	public void addMoney(Integer id, Double money) {
		String sql= "update ar_account set money = money + ? where id= ?";
		jt.update(sql,money,id);
	}

	@Override
	public void subMoney(Integer id, Double money) {
		String sql= "update ar_account set money = money - ? where id= ?";
		jt.update(sql,money,id);

	}

}

(7)创建AccountService接口类与实现类AccountServiceImpl

package com.linxin.spring.service;

public interface AccountService {
	void transfer(Integer from, Integer to,Double money);
}
package com.linxin.spring.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.linxin.spring.dao.AccountDao;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
	@Resource(name="accountDao")
	private AccountDao accountDao;
	@Override
	public void transfer(Integer from, Integer to, Double money) {
		accountDao.addMoney(to, money);
		int a=1/0;
		accountDao.subMoney(from, money);
	}

}

(8)创建spring配置文件application.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:centext="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.2.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
		<!-- 加入扫描 -->
		<centext:component-scan base-package="com.linxin.spring.dao"></centext:component-scan>
		<centext:component-scan base-package="com.linxin.spring.service"></centext:component-scan>
		<!-- 加载文件 -->
		<centext:property-placeholder location="classpath:db.properties"/>
		
		<!-- spring管理c3p0数据源 -->
		<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
			<property name="driverClass" value="${jdbc.driver}"></property>
			<property name="jdbcUrl" value="${jdbc.url}"></property>
			<property name="user" value="${jdbc.username}"></property>
			<property name="password" value="${jdbc.password}"></property>
		</bean>
		<!-- Jdbctemplate -->
		<bean name="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
			<property name="dataSource" ref="dataSource"></property>
		</bean>
		<!-- 事务管理 -->
		<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
			<!-- 数据源 -->
			<property name="dataSource" ref="dataSource"></property>
		</bean>
		<!-- 通知 -->
		<tx:advice id="txAdvice" transaction-manager="transactionManager">
			<tx:attributes>
				<!-- 传播行为 -->
				<!-- 支持当前事务,如果不存在,就新建一个 -->
				<tx:method name="transfer" propagation="REQUIRED"/>

			</tx:attributes>
		</tx:advice>
		<!-- 切面(将通知织入切入点) -->
		<aop:config>
			<!-- 切入点 -->
			<aop:pointcut expression="execution(* com.linxin.spring.service..*.*(..))" id="txPointcut"/>
			<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
		</aop:config>
</beans>

(9)测试类

package com.linxin.spring.Testtx;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.linxin.spring.service.AccountService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestTx {
	@Resource(name="accountService")
	private AccountService accountService;
	@Test
	public void testTransfer() {
		accountService.transfer(2, 1, 30.0);
	}

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring 中,可以使用 AOP(面向切面编程)和声明式事务管理来管理事务。 在声明式事务管理中,可以使用 @Transactional 注解来标记希望进行事务管理的方法或类。该注解可以用于类级别或方法级别,并且可以设置不同的传播行为、隔离级别和超时等属性。当使用 @Transactional 注解时,Spring 会自动为被标记的方法或类创建代理对象,在代理对象中添加事务管理的代码。 例如,以下代码演示了如何在 Spring 中使用声明式事务管理: ```java @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public void transferMoney(String fromUser, String toUser, double amount) { User from = userDao.getUserByName(fromUser); User to = userDao.getUserByName(toUser); from.setBalance(from.getBalance() - amount); to.setBalance(to.getBalance() + amount); userDao.updateUser(from); userDao.updateUser(to); } } ``` 在上面的示例中,@Transactional 注解用于 UserServiceImpl 类上,表示该类中的所有方法都将使用声明式事务管理。在 transferMoney() 方法中,当更新两个用户的余额时,如果发生异常,Spring 会自动回滚事务,确保转账操作在原子性和一致性方面的正确性。 注意,为了使声明式事务管理正常工作,需要在 Spring 配置文件中配置事务管理器和事务通知等相关组件。例如: ```xml <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="transferMoney" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="userServicePointcut" expression="execution(* com.example.UserService.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointcut"/> </aop:config> ``` 在上面的示例中,配置了一个 DataSourceTransactionManager 作为事务管理器,并使用 txAdvice 定义了一个事务通知。通过 aop:config 和 aop:advisor 将该事务通知织入到 UserService 中,以进行声明式事务管理

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值