-
-
Save amuguelove/9829bdaacf0c67c7df822f54baa46b18 to your computer and use it in GitHub Desktop.
Spring编程式事务
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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