What is the method for spring to initiate a transaction?
There are several ways to initiate transactions in Spring.
- suggestion
- configuration in AOP
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.example.service.*.*(..))" />
</aop:config>
- Declarative transaction management based on annotations: declaring transactions by using the @Transactional annotation on methods or classes.
@Transactional
public void saveUser(User user) {
// 保存用户操作
}
- Programmatic transaction management: Explicitly starting, committing, or rolling back transactions by writing code.
@Autowired
private PlatformTransactionManager transactionManager;
public void saveUser(User user) {
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(def);
try {
// 保存用户操作
transactionManager.commit(status);
} catch (RuntimeException e) {
transactionManager.rollback(status);
throw e;
}
}
- Combining declarative transaction management with programmatic transaction management: you can use the @Transactional annotation on methods or classes and use TransactionTemplate to operate transactions where programmatic transaction management is needed.
@Autowired
private TransactionTemplate transactionTemplate;
@Transactional
public void saveUser(User user) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
// 保存用户操作
}
});
}
These methods can be chosen based on specific needs, with annotation-based declarative transaction management being the most widely used and recommended method.