1、声明式事务,境搭建环。在pom.xml配置文件中新增依赖的jar包,导入相关依赖,数据源、数据驱动、Spring-jdbc模块。如下所示:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 4 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 <groupId>com.bie</groupId> 7 <artifactId>spring-tx-sourceCode</artifactId> 8 <version>0.0.1-SNAPSHOT</version> 9 10 11 <dependencies> 12 <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> 13 <dependency> 14 <groupId>org.springframework</groupId> 15 <artifactId>spring-context</artifactId> 16 <version>4.3.12.RELEASE</version> 17 </dependency> 18 <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> 19 <dependency> 20 <groupId>org.projectlombok</groupId> 21 <artifactId>lombok</artifactId> 22 <version>1.18.8</version> 23 <scope>provided</scope> 24 </dependency> 25 <!-- https://mvnrepository.com/artifact/javax.inject/javax.inject --> 26 <dependency> 27 <groupId>javax.inject</groupId> 28 <artifactId>javax.inject</artifactId> 29 <version>1</version> 30 </dependency> 31 <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> 32 <dependency> 33 <groupId>com.mchange</groupId> 34 <artifactId>c3p0</artifactId> 35 <version>0.9.5.2</version> 36 </dependency> 37 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> 38 <dependency> 39 <groupId>mysql</groupId> 40 <artifactId>mysql-connector-java</artifactId> 41 <version>5.1.44</version> 42 </dependency> 43 <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop --> 44 <dependency> 45 <groupId>org.springframework</groupId> 46 <artifactId>spring-aop</artifactId> 47 <version>4.3.12.RELEASE</version> 48 </dependency> 49 <dependency> 50 <groupId>org.springframework</groupId> 51 <artifactId>spring-aspects</artifactId> 52 <version>4.3.12.RELEASE</version> 53 </dependency> 54 <dependency> 55 <groupId>org.springframework</groupId> 56 <artifactId>spring-jdbc</artifactId> 57 <version>4.3.12.RELEASE</version> 58 </dependency> 59 60 </dependencies> 61 </project>
配置数据源,JdbcTemplate(Spring提供的简化数据库操作的工具)操作数据。使用@EnableTransactionManagement注解,开启基于注解的事务管理功能。配置事务管理器来控制事务,注册事务管理器PlatformTransactionManager到容器中。
1 package com.bie.tx; 2 3 import java.beans.PropertyVetoException; 4 5 import javax.sql.DataSource; 6 7 import org.springframework.context.annotation.Bean; 8 import org.springframework.context.annotation.ComponentScan; 9 import org.springframework.context.annotation.Configuration; 10 import org.springframework.jdbc.core.JdbcTemplate; 11 import org.springframework.jdbc.datasource.DataSourceTransactionManager; 12 import org.springframework.transaction.PlatformTransactionManager;