关于事务是什么学了数据库的都应该知道,在spring中如何完成事务的操作有两种方式,1是xml配置,2是注解开发,xml配置的我就不粘代码了,直接注解
1.首先创建配置类
@Configuration //你要扫描的项目包名 @ComponentScan(basePackages = "spring5") //开启事务的注解 @EnableTransactionManagement public class Config { //创建数据库的链接池 @Bean public DruidDataSource getDruidDataSource(){ DruidDataSource dataSource=new DruidDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("url"); dataSource.setUsername("root"); dataSource.setPassword("passowrd"); return dataSource; } //链接对象 @Bean public JdbcTemplate getjdbcTemplate(DruidDataSource dataSource){ JdbcTemplate jdbcTemplate=new JdbcTemplate(); jdbcTemplate.setDataSource(dataSource); return jdbcTemplate; } //事务管理器 @Bean public DataSourceTransactionManager getDataSourceTransactionManager(DruidDataSource dataSource){ DataSourceTransactionManager transactionManager=new DataSourceTransactionManager(); transactionManager.setDataSource(dataSource); return transactionManager; } }
2.Dao层
@Repository public class Userdaoimpl implements Userdao{ @Autowired private JdbcTemplate jdbcTemplate; @Override public void addmoney() { String sql="update t_acount set money=money-? where username=?"; jdbcTemplate.update(sql,50,"chenghaixiang"); } @Override public void reducemoney() { String sql="update t_acount set money=money+? where username=?"; jdbcTemplate.update(sql,50,"wang"); } }
3.service层
@Service @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ) public class UserService { @Autowired private Userdao userdao; public void zhuanzhang(){ userdao.addmoney(); //异常 //用来测试事务的 int i=10/0; userdao.reducemoney(); } }
4.测试
@Test public void test3(){ ApplicationContext context=new AnnotationConfigApplicationContext(Config.class); UserService userService=context.getBean("userService",UserService.class); userService.zhuanzhang(); }
测试结果应该是加了int i=10/0 。对数据库操作不成功
在service层中@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)这个注解是对事务操作的一些配置
如ioslation:事务隔离级别,propagation:事务传播行为等等