目录
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
@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;
}
}
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对象
@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;
}
}
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<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);
}
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;
}
@Override
public 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 {
@Autowired
private AccountDao accountDao;
@Autowired
private LogService logService;
@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){
//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 {
@Autowired
private LogDao logDao;
@Override
public 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<Account> 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 {
@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() throws IOException {
accountService.transfer("刘德华","周杰伦",50D);
}
}