1. Enable transaction management: enables transaction management
Add the @ EnableTransactionManagement annotation to the spring configuration class
@EnableTransactionManagement public class MainConfig4 { }
principle
@The EnableTransactionManagement annotation will enable spring to automatically manage transactions. With this annotation, the creation process of all beans will be intercepted during the startup of the spring container to determine whether the bean needs spring to manage transactions, that is, whether there is @ Transaction annotation in the bean. The judgment rules are as follows
1. Keep looking up along the class of the current bean, first from the current class, then the parent class, the parent class of the parent class, the interface of the current class, the parent interface of the interface, and the parent interface of the parent interface, and keep looking up to judge whether there is @ Transaction Annotation on these types
2. Is there a @ Transaction annotation on any public method of the class
If the bean meets any of the above rules, the spring container will create an agent through aop. An interceptor will be added to the agent. The interceptor will intercept the public method in the bean, start the transaction before the method is executed, and commit or roll back the transaction after the method is executed.
Let's take a look at the source code of enable transaction management
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(TransactionManagementConfigurationSelector.class) public @interface EnableTransactionManagement { /** * spring Transaction management is realized by creating proxy objects for bean s through aop * There are two ways to create proxy objects, jdk dynamic proxy and cglib proxy * proxyTargetClass: When it is true, cglib is forced to be used to create the proxy */ boolean proxyTargetClass() default false; /** * Used to specify the order of transaction interceptors * We know that many interceptors can be added to a method, and the interceptors can specify the order * For example, you can customize some interceptors to execute before or after the transaction interceptor, * You can control it through order */ int order() default Ordered.LOWEST_PRECEDENCE; }
2. Define transaction manager
If the transaction is managed by spring, you must create one or more transaction managers to manage specific transactions, such as starting a transaction, committing a transaction, and rolling back a transaction.
spring uses the platform transaction manager interface to represent the transaction manager.
Multiple implementation classes of PlatformTransactionManager are used to cope with different environments
Data source transaction manager: if you specify the data source, such as JdbcTemplate, mybatis and ibatis, you need to use this manager to help you control transactions. Others see the name and know the meaning
For example, if we use mybatis or JDBC template, define a transaction manager in the following way.
@Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); }
3. The @ Transaction annotation needs to be added to the target of the Transaction
@If the Transaction is placed on the interface, all public classes in the implementation class of the interface will be automatically added to the Transaction by spring
@If the Transaction is placed on the class, all pubilc methods in the current class and its infinite subclasses will be automatically added to the Transaction by spring
@If the Transaction is placed on the public method, the method will be automatically added to the Transaction by spring
Note: @ Transaction is only valid for public methods
@Introduction to Transactional parameters
4. Execute db Business Operations
When performing business operations on the @ Transaction annotation class or target methods, these methods will be automatically managed by spring.
For example, in the insertBatch operation below, delete the data first, and then insert the data in batch. The @ Transactional annotation is added to the method. At this time, the method will be automatically controlled by spring transactions, either successful or failed.
@Component public class UserService { @Autowired private JdbcTemplate jdbcTemplate; //Clear the data in the table first, and then insert the data in batches. Either both succeed or fail @Transactional public void insertBatch(String... names) { jdbcTemplate.update("truncate table t_user"); for (String name : names) { jdbcTemplate.update("INSERT INTO t_user(name) VALUES (?)", name); } } }
5. Start the spring container and use the bean to perform business operations
@Test public void test1() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(MainConfig4.class); context.refresh(); UserService userService = context.getBean(UserService.class); userService.insertBatch("java High concurrency series", "mysql series", "maven series", "mybatis series"); }
Complete case
Main configuration class:
@EnableTransactionManagement //Enable spring transaction management @Configuration //Specifies that the current class is a spring configuration class @ComponentScan //Open bean scan registration @PropertySource("/db/jdbc.properties") @Import(JdbcConfig.class) //It is not under one package, so it needs to be imported by @ Import public class MainConfig { }
JdbcConfig class
@Component 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; @Bean(name="jdbcTemplate") public JdbcTemplate creatJdbcTemplate(DataSource dataSource){ return new JdbcTemplate(dataSource); } @Bean(name="dataSource") public DataSource creatDataSource(){ DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(userName); ds.setPassword(passWord); return ds; } //Define a transaction manager @Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } }
Execute db Business Operation Service Class
@Component public class UserService { @Autowired private JdbcTemplate jdbcTemplate; @Transactional public int insertBeach(String ...names){ int result=0; for (String name : names) { // result += jdbcTemplate.update("INSERT INTO t_user(name) VALUES(?) ", name); result += jdbcTemplate.update("INSERT INTO t_user(name) VALUES (?)", name); } return result; } public List<Map<String,Object>> selectList(){ return jdbcTemplate.queryForList("SELECT * FROM t_user"); } }
Test class
@Test public void test(){ AnnotationConfigApplicationContext ioc = new AnnotationConfigApplicationContext(); ioc.register(MainConfig.class); ioc.refresh(); UserService bean = ioc.getBean(UserService.class); int count = bean.insertBeach( "java High concurrency series", "mysql series", "maven series", "mybatis series"); System.out.println(count+"strip"); System.out.println(bean.selectList()); }