What is the method for spring to initiate a transaction?

There are several ways to initiate transactions in Spring.

  1. suggestion
  2. 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>
  1. Declarative transaction management based on annotations: declaring transactions by using the @Transactional annotation on methods or classes.
@Transactional
public void saveUser(User user) {
    // 保存用户操作
}
  1. 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;
    }
}
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds