赞
踩
目录
2.ServiceAdvise(上一章节的AOP,这一章节没有使用,在Spring配置类里面注释了)
事务作用:在数据层保障一系列的数据库操作同成功同失败(一致性)
Spring事务:在数据层(dao)或业务层(service)保障一系列的数据库操作同成功同失败
进行保障的呢?(通过PlatformTransactionManager接口进行保障)
PlatformTransactionManager接口
- public interface PlatformTransactionManager {
-
- @Override
- public TransactionStatus getTransaction(TransactionDefinition transactionDefinition) throws TransactionException {
- return null;
- }
- @Override
- public void commit(TransactionStatus transactionStatus) throws TransactionException {
-
- }
- @Override
- public void rollback(TransactionStatus transactionStatus) throws TransactionException {
-
- }
- }
PlatformTransactionManager接口的实现类(DataSourceTransactionManager)
需求:实现任意两个账户之间的转账操作
需求微缩:A账户减钱,B账户加钱
ps:真正的银行转账有三个用户,a转b,b转c
1.数据层提供基础操作,指定账户减钱(outMoney),指定账户加钱(inmoney)
2.业务层提供转账操作(transfer),调用减钱与加钱的操作
3.提供两个账号和操作金额执行转账操作
4.基于Spring整合MyBatis环境搭建上述操作
1.程序正常执行时,账户金额A加B减,程序正常
2.程序出现异常之后,转账失败,但是异常之前的得操作成功,异常之后得操作失败,整体业务失败
注意事项:
1.Spring注解式事务通常添加在业务层接口中,而不会添加在业务层得实现类中,降低耦合
2.注解式事务可以添加到业务层方法上,表示为此方法开启事务。也可以添加到业务层接口上,表示当前接口的所有方法都开启事务
- @Transactional
- void transfer(String out,String in ,Double money) ;
注意事项:
1.事务管理器要根据实现技术进行选择
2.MyBtis框架使用的式Jdbc事务
- //事务管理器
- @Bean
- public PlatformTransactionManager transactionManager(DataSource dataSource){
- //一个bean需要外部资源怎么办,引用注入帮你解决问题
- DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
- transactionManager.setDataSource(dataSource);
- return transactionManager;
- }
- package com.itheima.config;
-
- import org.springframework.context.annotation.*;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
-
- @Configuration //代表了这是个配置类,以此与applicationContext.xml基础配置文件相当
- @ComponentScan("com.itheima") //包扫描
- @PropertySource("jdbc.properties") //加载properties配置文件
- @Import({JdbcConfig.class,MybatisConfig.class}) //加载JdbcConfig,MybatisConfig配置类
- //@EnableAspectJAutoProxy //启动AOP的注解,切面
- @EnableTransactionManagement //启动事务管理,加载相对应的事务
- public class SpringConfig {
- }
- package com.itheima.aop;
-
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.Signature;
- import org.aspectj.lang.annotation.Around;
- import org.aspectj.lang.annotation.Aspect;
- import org.aspectj.lang.annotation.Pointcut;
- import org.springframework.stereotype.Component;
-
-
- public class ServiceAdvise {
-
- //定义切入点,切入点时Service里面的所有方法,
- @Pointcut("execution(* com.itheima.service.*Service.*(..))")
- private void servicePt(){}
-
- //把切入点servicePt()与通知runSpeed()进行绑定
- @Around("ServiceAdvise.servicePt()")
- public void runSpeed(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
- long star = System.currentTimeMillis();
- Signature signature = proceedingJoinPoint.getSignature();//代表了一次执行的签名信息
- String name = signature.getName(); //方法名
- Class declaringType = signature.getDeclaringType(); //表示方法的接口名
- for (int i = 0; i < 10000; i++) {
- proceedingJoinPoint.proceed();
- }
- Object proceed = proceedingJoinPoint.proceed();//调取原始操作,即时AccountServiceImpl的返回值
- long end = System.currentTimeMillis();
- System.out.println("业务层接口"+declaringType+"的"+name+"方法,执行万次的测试为"+(end - star)+"ms");
- }
-
-
- }
- package com.itheima.config;
-
- import com.alibaba.druid.pool.DruidDataSource;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.jdbc.datasource.DataSourceTransactionManager;
- import org.springframework.transaction.PlatformTransactionManager;
-
- import javax.sql.DataSource;
-
- public class JdbcConfig {
-
- @Value("${jdbc.driver}")
- private String driver;
- @Value("${jdbc.url}")
- private String url;
- @Value("${jdbc.username}")
- private String username;
- @Value("${jdbc.password}")
- private String password;
-
- //1.定义一个方法获取响应的bean
- //2.添加@Bean,表示当前方法的返回值是一个bean
- @Bean
- public DataSource dataSource(){
- DruidDataSource ds = new DruidDataSource();
- ds.setDriverClassName(driver);
- ds.setUrl(url);
- ds.setUsername(username);
- ds.setPassword(password);
- return ds;
- }
-
- //事务管理器
- @Bean
- public PlatformTransactionManager transactionManager(DataSource dataSource){
- //一个bean需要外部资源怎么办,引用注入帮你解决问题
- DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
- transactionManager.setDataSource(dataSource);
- return transactionManager;
- }
- }
- package com.itheima.config;
-
- import org.springframework.context.annotation.*;
- import org.springframework.transaction.annotation.EnableTransactionManagement;
-
- @Configuration //代表了这是个配置类,以此与applicationContext.xml基础配置文件相当
- @ComponentScan("com.itheima") //包扫描
- @PropertySource("jdbc.properties") //加载properties配置文件
- @Import({JdbcConfig.class,MybatisConfig.class}) //加载JdbcConfig,MybatisConfig配置类
- //@EnableAspectJAutoProxy //启动AOP的注解,切面
- @EnableTransactionManagement //启动事务管理,加载相对应的事务
- public class SpringConfig {
- }
- package com.itheima.config;
-
- import org.mybatis.spring.SqlSessionFactoryBean;
- import org.mybatis.spring.mapper.MapperScannerConfigurer;
- import org.springframework.context.annotation.Bean;
-
- import javax.sql.DataSource;
-
- public class MybatisConfig {
- //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
- @Bean
- public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){//这里得DataSource是代表着引用注入,jdbcConfig
- SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
- ssfb.setTypeAliasesPackage("com.itheima.domain");//问实体类的位置,,扫描类型别名的包
- ssfb.setDataSource(dataSource);//替代的是jdbcConfig中的DataSource,也就是详细配置信息
- return ssfb;
- }
- //定义bean,返回MapperScannerConfigurer对象
- @Bean
- public MapperScannerConfigurer mapperScannerConfigurer(){
- MapperScannerConfigurer msc = new MapperScannerConfigurer();
- msc.setBasePackage("com.itheima.dao");//问映射在什么位置,由于注解完成了执行语句,所以不需要有映射文件
- return msc;
- }
- }
-
-
-
- package com.itheima.dao;
-
- import com.itheima.domain.Account;
- import org.apache.ibatis.annotations.*;
-
- import java.util.List;
-
- public interface AccountDao {
-
- @Insert("insert into account(username,password)values(#{username},#{password})")
- void save(Account account);
-
- @Delete("delete from account where id = #{id} ")
- void delete(Integer id);
-
- @Update("update account set username = #{username} , password = #{password} where id = #{id} ")
- void update(Account account);
-
- @Select("select * from account")
- List<Account> findAll();
-
- @Select("select * from account where id = #{id} ")
- Account findById(Integer id);
-
- @Update("update account set money = money + #{money} where name = #{name}")
- void inMoney(@Param("name") String name, @Param("money") Double money);
-
- @Update("update account set money = money - #{money} where name = #{name}")
- void outMoney(@Param("name") String name, @Param("money") Double money);
-
- }
- package com.itheima.domain;
-
- import java.io.Serializable;
-
- public class Account implements Serializable {
-
- private Integer id;
- private String name;
- private Double money;
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public Double getMoney() {
- return money;
- }
-
- public void setMoney(Double money) {
- this.money = money;
- }
-
- @Override
- public String toString() {
- return "Account{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", money=" + money +
- '}';
- }
- }
- package com.itheima.service.impl;
-
- import com.itheima.dao.AccountDao;
- import com.itheima.domain.Account;
- import com.itheima.service.AccountService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
- @Service
- public class AccountServiceImpl implements AccountService {
-
- @Autowired
- private AccountDao accountDao;
- @Override
- public void save(Account account) {
- accountDao.save(account);
- }
- @Override
- public void update(Account account){
- accountDao.update(account);
- }
- @Override
- public void delete(Integer id) {
- accountDao.delete(id);
- }
- @Override
- public Account findById(Integer id) {
- return accountDao.findById(id);
- }
- @Override
- public List<Account> findAll() {
- return accountDao.findAll();
- }
- @Override
- public void transfer(String out, String in, Double money) {
- accountDao.outMoney(out,money);
- int i = 1/0;
- accountDao.inMoney(in,money);
- }
- }
- package com.itheima.service;
-
- import com.itheima.domain.Account;
- import org.springframework.transaction.annotation.Transactional;
-
- import java.util.List;
-
- public interface AccountService {
-
- void save(Account account);
-
- void delete(Integer id);
-
- void update(Account account);
-
- List<Account> findAll();
-
- Account findById(Integer id);
-
- @Transactional
- void transfer(String out,String in ,Double money) ;
-
- }
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url= jdbc:mysql://localhost:3306/db1?useSSL=false
- jdbc.username=root
- jdbc.password=root
- package com.itheima.service;
-
- import com.itheima.config.SpringConfig;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.test.context.ContextConfiguration;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
- @RunWith(SpringJUnit4ClassRunner.class) //设置专用的类运行器
- @ContextConfiguration(classes = SpringConfig.class) //指定Spring文件的配置类
- public class AccountServiceTest {
-
- @Autowired
- private AccountService accountService;
-
- @Test
- public void testFindById(){
- System.out.println(accountService.findById(2));
- }
-
- @Test
- public void testFindAll(){
- System.out.println(accountService.findAll());
- }
-
- @Test
- public void testTransfer() {
- accountService.transfer("刘德华","周杰伦",100D);
- }
- }
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>org.example</groupId>
- <artifactId>Spring-demo1-lifeCycle</artifactId>
- <version>1.0-SNAPSHOT</version>
-
- <properties>
- <maven.compiler.source>18</maven.compiler.source>
- <maven.compiler.target>18</maven.compiler.target>
- </properties>
-
- <dependencies>
- <!--springFramework依赖,,,,由于AOP包与Context有依赖关系,所以不需要在进行导入aop的包-->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>5.3.23</version>
- </dependency>
- <dependency>
- <groupId>javax.annotation</groupId>
- <artifactId>javax.annotation-api</artifactId>
- <version>1.3.2</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.2.11</version>
- </dependency>
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.5.6</version>
- </dependency>
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.46</version>
- </dependency>
- <!-- Spring操作数据库有关的都要导这个包-->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>5.0.0.RELEASE</version>
- </dependency>
- <!-- Spring 整合mybtis的包,这个包是和mybatis的包版本是相对应的-->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- <version>1.3.0</version>
- </dependency>
- <!-- junit包-->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <!-- Spring 操作test的 包-->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>5.2.10.RELEASE</version>
- </dependency>
- <!-- 导入Aspect(切面)的包-->
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>1.8.8</version>
- </dependency>
- </dependencies>
- </project>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。