1. springdatajpa手动控制事务,开启,提交,回滚
定义事务接口,开启提交回滚
import java.util.concurrent.Callable;
public interface TransactionService {
void begin();
void commit();
void rollback();
/**
* 在事务中执行回调函数
*
* @param callable 回调函数
*/
<V> V execute(Callable<V> callable);
}
实现事务接口
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.util.concurrent.Callable;
@Service
public class TransactionServiceImpl implements TransactionService {
@Autowired
private PlatformTransactionManager transactionManager;
private ThreadLocal<TransactionStatus> threadLocal = new ThreadLocal<>();
@Override
public void begin() {
TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
threadLocal.set(transactionManager.getTransaction(transactionDefinition));
}
@Override
public void commit() {
transactionManager.commit(threadLocal.get());
threadLocal.remove();
}
@Override
public void rollback() {
transactionManager.rollback(threadLocal.get());
threadLocal.remove();
}
@Override
public <V> V execute(Callable<V> callable) {
try {
begin();
V result = callable.call();
commit();
return result;
} catch (Exception e) {
rollback();
throw new RuntimeException(e);
}
}
}
示例
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private TransactionService transactionService;
@Override
public void add(String userName, String password) {
UserEntity userEntity = new UserEntity();
userEntity.setUsername("test");
userEntity.setPassword("test123");
transactionService.execute(() -> userRepository.save(userEntity));
}
@Override
public void add1(){
UserEntity userEntity = new UserEntity();
userEntity.setUsername("test");
userEntity.setPassword("test123");
//手动开启事务
transactionService.begin();
try {
userRepository.save(userEntity);
//手动提交事务
transactionService.commit();
} catch (TransactionException e) {
//手动回滚事务
//最好是放在catch 里面,防止程序异常而事务一直卡在哪里未提交
transactionService.rollback();
new RuntimeException("统一事务处理");
}
}