目录
1、依赖引入(pom文件):
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xyz.jangle</groupId>
<artifactId>spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<spring.version>5.2.2.RELEASE</spring.version><!-- 声明spring版本号 -->
</properties>
<dependencies>
<!-- 0.引入JDBC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 1.Spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<!-- 设置MAVEN的编译的JDK版本为1.8 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
2.1、创建模拟转账的功能接口
package spring.m6_3.service;
/**
* @author jangle
* @email jangle@jangle.xyz
* @time 2022年10月8日 上午9:30:53
*
*/
public interface AccountService {
/**
* 转账
* @author jangle
* @time 2022年10月8日 上午10:04:48
* @param sourceId
* @param targetId
* @param amount
*/
void transferMoney(long sourceId, long targetId, double amount);
}
2.2、实现2.1的接口方法
package spring.m6_3.service.impl;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.transaction.annotation.Transactional;
import spring.m6_3.service.AccountService;
/**
* @author jangle
* @email jangle@jangle.xyz
* @time 2022年10月8日 上午9:36:41
*
*/
public class AccountServiceJdbcTxImplWithSpring implements AccountService{
private DataSource dataSource;
@Override
@Transactional
public void transferMoney(long sourceId,long targetId,double amount) {
// 必须使用DataSourceUtils来获取连接,否则无法使用事务功能。
Connection connection = DataSourceUtils.getConnection(dataSource);
try {
//如果使用普通的连接,那么转账后异常时,转账依旧生效(不会回滚)
// Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
statement.executeUpdate("update table_a set balance = balance - "+amount+" where "
+ "id = "+ sourceId);
statement.executeUpdate("update table_a set balance = balance + "+amount+" where "
+ "id = "+ targetId);
// throw new RuntimeException(); // 如果在此处添加异常,则上面的SQL转账功能将会不生效(会回滚)。
} catch (SQLException e) {
throw new RuntimeException();
} finally {
DataSourceUtils.releaseConnection(connection, dataSource);
}
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}
3、创建Spring配置文件(基于Java的文件)
package spring.m6_3;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import spring.m6_3.service.AccountService;
import spring.m6_3.service.impl.AccountServiceJdbcTxImplWithSpring;
/**
* @author jangle
* @email jangle@jangle.xyz
* @time 2022年10月8日 上午9:53:28
*
*/
@Configuration
@EnableTransactionManagement
public class Configuration6_3 {
/**
* 配置数据源
*
* @author jangle
* @time 2022年10月8日 上午11:13:54
* @return
*/
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=UTF8");
dataSource.setUsername("jangle_demo");
dataSource.setPassword("1");
return dataSource;
}
/**
* 1.必须创建这个事务对象,spring的事务管理功能才可用。
* 2.spring通过“类型”自动装配,所以不用担心取名的问题以及配置的问题。
* @author jangle
* @time 2022年10月8日 上午10:22:18
* @return
*/
@Bean
public PlatformTransactionManager transactionManager() {
DataSourceTransactionManager manager = new DataSourceTransactionManager();
manager.setDataSource(dataSource());
return manager;
}
@Bean
public AccountService accountService() {
AccountServiceJdbcTxImplWithSpring bean = new AccountServiceJdbcTxImplWithSpring();
bean.setDataSource(dataSource());
return bean;
}
}
4、创建主程序对代码进行测试。
package spring.m6_3;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import spring.m6_3.service.AccountService;
/**
*
* 6.3、使用Spring的声明式事务管理(DEMO)。
* @author jangle
* @email jangle@jangle.xyz
* @time 2022年10月8日 上午10:08:50
*
*/
public class M {
@SuppressWarnings("resource")
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Configuration6_3.class);
AccountService accountService = context.getBean(AccountService.class);
accountService.transferMoney(1L, 2L, 5.0d);
System.out.println("完成转账。");
}
}
5.1、附1:数据库表结构
CREATE TABLE `table_a` (
`id` INT(10) UNSIGNED NOT NULL,
`name` VARCHAR(50) NOT NULL DEFAULT '' COLLATE 'utf8_general_ci',
`age` INT(11) NULL DEFAULT NULL,
`address` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8_general_ci',
`balance` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
)
5.2、附2:源代码地址:
GitHub - bof-jangle/beginningSpring: Spring 入门经典
参考文献:《Spring 入门经典》