常用的Bean注解,通过注解定义Bean
- .@Component.
- @Repository.
- @Service.
- @Controller
- ·@RestController
?
Spring事务
一致的事务模型,屏蔽差异性。 · JDBC/Hibernate/myBatis . DataSource/JTA
?传播特性
?事务隔离级别
Spring默认以数据库的隔离级别为准,默认值-1;
?Spring编程式事务
@SpringBootApplication
@Slf4j
public class ProgrammaticTransactionDemoApplication implements CommandLineRunner {
@Autowired
private TransactionTemplate transactionTemplate;
@Autowired
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(ProgrammaticTransactionDemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
log.info("COUNT BEFORE TRANSACTION: {}", getCount());
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
jdbcTemplate.execute("INSERT INTO FOO (ID, BAR) VALUES (1, 'aaa')");
log.info("COUNT IN TRANSACTION: {}", getCount());
transactionStatus.setRollbackOnly();
}
});
log.info("COUNT AFTER TRANSACTION: {}", getCount());
}
private long getCount() {
return (long) jdbcTemplate.queryForList("SELECT COUNT(*) AS CNT FROM FOO")
.get(0).get("CNT");
}
}
?Spring声明式事务
事务失效:?默认情况下,只有来自外部的方法调用才会被AOP代理捕获,也就是,类内部方法调用本类内部的其他方法并不会引起事务行为,必须是代理对象调用才可以!即使被调用方法使用@Transactional注解进行修饰。
?
?
@Component
public class FooServiceImpl implements FooService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
@Transactional
public void insertRecord() {
jdbcTemplate.execute("INSERT INTO FOO (BAR) VALUES ('AAA')");
}
@Override
@Transactional(rollbackFor = RollbackException.class)
public void insertThenRollback() throws RollbackException {
jdbcTemplate.execute("INSERT INTO FOO (BAR) VALUES ('BBB')");
throw new RollbackException();
}
@Override
public void invokeInsertThenRollback() throws RollbackException {
insertThenRollback(); // 事务失效,内部调用而非代理调用,解决,FooServiceImpl自己注入自己
}
}
?
|