Spring事务配置(案例:转账业务追加日志,事务传播行为)
创始人
2024-02-07 15:22:18
0

目录

Spring事务配置 

案例

事务传播行为

 代码实现:

1.文件大致格式:

 2.ServiceAdvise(AOP功能包)

3.JdbcConfig(jdbc配置文件,包含了事务管理器)

4.MybatisConfig(mybatis配置文件)

5.SpringConfig(Spring配置文件)

6.AccountDao(账户的数据层文件)

7.LogDao(日志的数据层文件)

8.Account(实体类)

9.AccountServiceImpl(业务层实现类,转账)

10.LogServiceImpl(业务层实现类,日志)

11.AccountService(业务层接口,转账)

12.LogService(业务层接口,日志)

13jdbc.properties(jdbc配置信息)

14.AccountSerrviceTest(测试类)


Spring事务配置 

如果相对Spring事务进行精细化处理的话,可以看下表。

 1.readOnly,默认为false

  @Transactional(readOnly = true)void transfer(String out,String in ,Double money) ;

2.rollbackFor(遇到指定异常回滚)

 //开启事务@Transactional(rollbackFor = {IOException.class})//表示遇到IOE就会滚,不执行任何语句,可以直接throw Exception最高级,遇见就会回滚void transfer(String out,String in ,Double money) throws IOException;

案例

需求:实现任意两个账户之间的转账操作,并对每次转账操作在数据库进行留痕

需求微缩:A账户减钱,B账户加钱,数据库记录日志

分析:

1.基于转账操作的案例添加日志模块,实现数据库中记录日志

2.业务层转账操作(transfer),调用减钱,加钱与记录日志功能

实现效果预期:

无论转账操作是否成功,均进行转账操作的日志留痕

存在的问题:

日志的记录与转账操作同属于一个事务,同成功,同失败

实习啊效果预期改进:

无论转账操作是否成功,日志必须保留

事务传播行为

事务协调员对事务管理员所携带事务的处理态度

也是是事务协调员有权力不参与到事务管理员的管理之中

@Transactional(propagation = Propagation.REQUIRES_NEW)

 代码实现:

1.文件大致格式:

 2.ServiceAdvise(AOP功能包)

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");}}

3.JdbcConfig(jdbc配置文件,包含了事务管理器)

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@Beanpublic DataSource dataSource(){DruidDataSource ds = new DruidDataSource();ds.setDriverClassName(driver);ds.setUrl(url);ds.setUsername(username);ds.setPassword(password);return ds;}//事务管理器@Beanpublic PlatformTransactionManager transactionManager(DataSource dataSource){//一个bean需要外部资源怎么办,引用注入帮你解决问题DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();transactionManager.setDataSource(dataSource);return transactionManager;}
}

4.MybatisConfig(mybatis配置文件)

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对象@Beanpublic SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){//这里得DataSource是代表着引用注入,jdbcConfigSqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();ssfb.setTypeAliasesPackage("com.itheima.domain");//问实体类的位置,,扫描类型别名的包ssfb.setDataSource(dataSource);//替代的是jdbcConfig中的DataSource,也就是详细配置信息return ssfb;}//定义bean,返回MapperScannerConfigurer对象@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc = new MapperScannerConfigurer();msc.setBasePackage("com.itheima.dao");//问映射在什么位置,由于注解完成了执行语句,所以不需要有映射文件return msc;}
}

5.SpringConfig(Spring配置文件)

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 {
}

6.AccountDao(账户的数据层文件)

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 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);}

7.LogDao(日志的数据层文件)

package com.itheima.dao;import org.apache.ibatis.annotations.Insert;public interface LogDao {@Insert("insert into log (info,createDate) values(#{info},now())")void log(String info);
}

8.Account(实体类)

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;}@Overridepublic String toString() {return "Account{" +"id=" + id +", name='" + name + '\'' +", money=" + money +'}';}
}

9.AccountServiceImpl(业务层实现类,转账)

package com.itheima.service.impl;import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import com.itheima.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;@Autowiredprivate LogService logService;@Overridepublic void save(Account account) {accountDao.save(account);}@Overridepublic void update(Account account) {accountDao.update(account);}@Overridepublic void delete(Integer id) {accountDao.delete(id);}@Overridepublic Account findById(Integer id) {return accountDao.findById(id);}@Overridepublic List findAll() {return accountDao.findAll();}@Overridepublic void transfer(String out, String in, Double money){//try catch是为了  让logService代码必须运行try{accountDao.outMoney(out, money);int i = 1 / 0 ;accountDao.inMoney(in, money);}finally {logService.log(out,in,money);}}
}

10.LogServiceImpl(业务层实现类,日志)

package com.itheima.service.impl;import com.itheima.dao.LogDao;
import com.itheima.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class LogServiceImpl implements LogService {@Autowiredprivate LogDao logDao;@Overridepublic void log(String out, String in, Double money) {logDao.log("转账操作由" + out + "到" + in + ",金额" + money);}
}

11.AccountService(业务层接口,转账)

package com.itheima.service;import com.itheima.domain.Account;
import org.springframework.transaction.annotation.Transactional;import java.io.IOException;
import java.util.List;public interface AccountService {void save(Account account);void delete(Integer id);void update(Account account);List findAll();Account findById(Integer id);//开启事务@Transactional(rollbackFor = {IOException.class})//表示遇到IOE就会滚,不执行任何语句,可以直接throw Exception最高级,遇见就会回滚void transfer(String out,String in ,Double money);}

12.LogService(业务层接口,日志)

package com.itheima.service;import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;public interface LogService {@Transactional(propagation = Propagation.REQUIRES_NEW)void log(String out,String in,Double money);
}

13jdbc.properties(jdbc配置信息)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url= jdbc:mysql://localhost:3306/db1?useSSL=false
jdbc.username=root
jdbc.password=root

14.AccountSerrviceTest(测试类)

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;import java.io.IOException;@RunWith(SpringJUnit4ClassRunner.class)              //设置专用的类运行器
@ContextConfiguration(classes = SpringConfig.class)  //指定Spring文件的配置类
public class AccountServiceTest {@Autowiredprivate AccountService accountService;@Testpublic void  testFindById(){System.out.println(accountService.findById(2));}@Testpublic  void  testFindAll(){System.out.println(accountService.findAll());}@Testpublic void testTransfer() throws IOException {accountService.transfer("刘德华","周杰伦",50D);}
}

上一篇:喝酒醉的古诗

下一篇:什么样的日影

相关内容

热门资讯

川渝首个跨地域跨层级诉讼服务中... 8月28日,川渝首个跨地域、跨层级诉讼服务中心——川渝高竹新区一体化诉讼服务中心正式揭牌运行。 揭...
伊朗外长:欧洲三国启动“快速恢... 当地时间8月28日,伊朗外长阿拉格齐与英、法、德三国外长,以及欧盟外交与安全政策高级代表通电话。 欧...
国防部:大学生应征入伍可享这些... 8月28日下午,国防部举行例行记者会,国防部新闻发言人张晓刚大校答记者问。 记者:当前正处于征兵季,...
个人条款都已达协议!德天空:利... 直播吧08月28日讯 据德天空记者普莱腾贝格消息,利物浦仍准备在关窗前签下伊萨克+格伊。 记者表示,...
8月29日零时起 前往北京车次... 8月29日零时起,北京将实行落地检,即时起西安站、西安北站部分车次将进行二次安检。 什么是二次安检...
严打枪爆违法犯罪!广东公安缴获... 为确保第十五届全国运动会和全国第十二届残疾人运动会暨第九届特殊奥林匹克运动会安全顺利举行,广东省公安...
重磅政策落地!利好南京江北新区 扬子晚报网8月28日讯(记者 刘丽媛)8月27日,商务部、江苏省人民政府正式印发了《中国(江苏)自由...
新学期要开始了!这些政策值得关... 南靖在线--贴近民生、服务百姓。为您推送南靖乡讯、停电、停水通知等便民服务信息;关注三农、百姓衣食住...
浙江严打网络犯罪 今年以来抓获... 中新网杭州8月28日电 (钱晨菲 吴怡欣)8月28日,浙江召开“之江净网”网络空间依法治理新闻发布会...
调解婚恋纠纷 楚雄两司法所合力... “离婚是你单方面提出的,彩礼我是不可能退的!”“我们才结婚7个月,我有权要求将彩礼全额退还给我。”近...