springboot 开启事务以及手动提交事务
需要在服务类上加上两个注解
@Autowired
DataSourceTransactionManager dataSourceTransactionManager;
@Autowired
TransactionDefinition transactionDefinition;
手动开启事务
TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
手动提交事务
dataSourceTransactionManager.commit(transactionStatus);//提交
手动回滚事务
dataSourceTransactionManager.rollback(transactionStatus);//最好是放在catch 里面,防止程序异常而事务一直卡在哪里未提交
package com.java.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import com.java.entity.User;
import com.java.service.impl.UserServiceImpl;
@Controller
@RequestMapping(value = "/p")
public class tt {
@Autowired
public UserServiceImpl t;
@Autowired
DataSourceTransactionManager dataSourceTransactionManager;
@Autowired
TransactionDefinition transactionDefinition;
@RequestMapping(value = "/test")
public void jj(){
TransactionStatus transactionStatus=null;
try {
transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
User user=new User();
user.setId("12");
user.setUsername("nihao");
user.setPassword("12346");
t.insert(user);
System.out.println("加油");
dataSourceTransactionManager.commit(transactionStatus);//提交
TransactionStatus transactionStatus2 = dataSourceTransactionManager.getTransaction(transactionDefinition);
User user2=new User();
user2.setId("12");
user2.setUsername("nihao");
user2.setPassword("12346");
t.insert(user2);
dataSourceTransactionManager.commit(transactionStatus2);//提交
} catch (Exception e) {
if(transactionStatus!=null){
dataSourceTransactionManager.rollback(transactionStatus);
}
e.printStackTrace();
}
}
@RequestMapping(value = "/test2")
public void jj2(){
TransactionStatus transactionStatus=null;
try {
transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
User user=new User();
user.setId("12");
user.setUsername("nihao");
user.setPassword("12346");
t.insert(user);
System.out.println("加油");
/*dataSourceTransactionManager.commit(transactionStatus);//提交
TransactionStatus transactionStatus2 = dataSourceTransactionManager.getTransaction(transactionDefinition);*/
User user2=new User();
user2.setId("12");
user2.setUsername("nihao");
user2.setPassword("12346");
t.insert(user2);
dataSourceTransactionManager.commit(transactionStatus);//提交
} catch (Exception e) {
if(transactionStatus!=null){
dataSourceTransactionManager.rollback(transactionStatus);
}
e.printStackTrace();
}
}
}