Spring事务也算是面试中经常遇到的一个小知识点吧,关注的点有以下几个:
下面简单写点案例,回顾一下;
一、通过配置文件来配置事务
1.导入jar包(这里直接导入了Spring boot相关jar)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-parent</artifactId>
<version>2.2.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.4.11</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
</dependencies>
2.创建用户类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String userName;
private int amount;
}
3.创建service接口
public interface UserService {
public User getUser(int id);
public List<User> getAllUser();
public boolean delUser(int id);
public boolean updUser(User user);
public boolean insertUser(User user);
}
4.创建UserService接口实现类
public class UserServiceImpl implements UserService {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
this.jdbcTemplate = jdbcTemplate;
}
public User getUser(int id) {
return null;
}
public List<User> getAllUser() {
return null;
}
public boolean delUser(int id) {
return false;
}
public boolean updUser(User user) {
return false;
}
public boolean insertUser(User user) {
int insert = jdbcTemplate.update("insert into user(user_name,amount) values(?,?)", "xiaowu", 100);
int i = 1 / 0;
return true;
}
}
5.配置applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- don't forget the DataSource -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/my_db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- this is the service object that we want to make transactional -->
<bean id="userService" class="com.service.impl.UserServiceImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
<!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true"/>
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- ensure that the above transactional advice runs for any execution
of an operation defined by the UserService interface -->
<aop:config>
<aop:pointcut id="userServiceOperation" expression="execution(* com.service.impl.UserServiceImpl.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServiceOperation"/>
</aop:config>
<!-- similarly, don't forget the TransactionManager -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- other <bean/> definitions here -->
</beans>
6.测试
public class ApplicationStart {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = ctx.getBean(UserService.class);
userService.insertUser(new User());
}
}
数据插入成功,日志及表数据如下:
修改UserServiceImpl代码如下:
public boolean insertUser(User user) {
int insert = jdbcTemplate.update("insert into user(user_name,amount) values(?,?)", "xiaowu", 100);
int i = 1 / 0;
return true;
}
再次测试,日志结果如下:
此时表里面也没有新数据插入,事务回滚。
二、Springboot注解配置事务
1.创建application.properties,配置数据库连接;
spring.datasource.url=jdbc:mysql://localhost:3306/my_db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
2.修改UserServiceImpl代码如下:
@Transactional(rollbackFor=Exception.class)
public boolean insertUser(User user) {
int insert = jdbcTemplate.update("insert into user(user_name,amount) values(?,?)", "xiaowu", 100);
return true;
}
3.测试
@SpringBootApplication
@EnableTransactionManagement
public class ApplicationStart {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(ApplicationStart.class,args);
UserService userService = (UserService) context.getBean("userService");
userService.insertUser(new User());
}
}
数据插入成功;
修改UserServiceImpl代码如下:
@Transactional(rollbackFor=Exception.class)
public boolean insertUser(User user) {
int insert = jdbcTemplate.update("insert into user(user_name,amount) values(?,?)", "xiaowu", 100);
int i = 1 / 0;
return true;
}
再次运行,表里面未新增新数据,事务回滚:
这里在简单测试一下其默认的事务传播机制,修改UserServiceImpl代码如下:
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private UserService userService2;
@Transactional(rollbackFor=Exception.class)
public boolean insertUser(User user) {
int insert = jdbcTemplate.update("insert into user(user_name,amount) values(?,?)", "xiaolong", 1100);
userService2.insertUser(new User());
return true;
}
public User getUser(int id) {
return null;
}
public List<User> getAllUser() {
return null;
}
public boolean delUser(int id) {
return false;
}
public boolean updUser(User user) {
return false;
}
}
拷贝一份UserServiceImpl,改名为UserServiceImpl2
@Service("userService2")
public class UserServiceImpl2 implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional(rollbackFor=Exception.class,propagation= Propagation.REQUIRED)
public boolean insertUser(User user) {
int insert = jdbcTemplate.update("insert into user(user_name,amount) values(?,?)", "xiaoqian", 1200);
int i = 1 / 0;
return true;
}
public User getUser(int id) {
return null;
}
public List<User> getAllUser() {
return null;
}
public boolean delUser(int id) {
return false;
}
public boolean updUser(User user) {
return false;
}
}
运行程序,数据未成功插入,将int i = 1/0;拷贝道UserServiceImpl中
@Transactional(rollbackFor=Exception.class)
public boolean insertUser(User user) {
int insert = jdbcTemplate.update("insert into user(user_name,amount) values(?,?)", "xiaolong", 1100);
userService2.insertUser(new User());
int i = 1 / 0;
return true;
}
运行效果一样,数据也未插入表中;其它场景也很简单,这里就不做测试了;
总结:Spring事务相对简单,平时写些demo即可,官网里面有一个调用流程的视图,可以简单看看