Skip to content

Instantly share code, notes, and snippets.

@amuguelove
Created November 19, 2023 14:46
Show Gist options
  • Save amuguelove/9829bdaacf0c67c7df822f54baa46b18 to your computer and use it in GitHub Desktop.
Save amuguelove/9829bdaacf0c67c7df822f54baa46b18 to your computer and use it in GitHub Desktop.
Spring编程式事务
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.function.Supplier;
@Component
@RequiredArgsConstructor
public class TransactionWrap {
private final PlatformTransactionManager platformTransactionManager;
/**
* 执行目标代码使用指定的事务传播级别,运行方法无返回值
*/
public void doInTransaction(Propagation propagation, Runnable runnable) {
TransactionTemplate template = new TransactionTemplate(platformTransactionManager);
template.setPropagationBehavior(propagation.value());
template.executeWithoutResult(run -> {
runnable.run();
});
}
/**
* 执行目标代码使用指定的事务传播级别,运行方法有返回值
*/
public <T> T doInTransaction(Propagation propagation, Supplier<T> supplier) {
TransactionTemplate template = new TransactionTemplate(platformTransactionManager);
template.setPropagationBehavior(propagation.value());
return template.execute((status) -> supplier.get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment