Spring Mvc 中使用@transactional 的事务数

Number of transactions using @transactional in Spring Mvc

我是 spring-mvc-hibernate 的初学者,我有一个控制器,它在我的 spring mvc 中调用了很多 daoimpl 方法,这些方法由 @Transactional 注释它是否进行往返每种方法还是只做一种?

代码如下所示:Hibernate 用于处理所有调用

CustomerEntity customerEntity = (CustomerEntity) customerService.getCustomerFromLeadId(id);
AddressEntity resAddressEntity = (AddressEntity) addressService.getResAddress(customerEntity.getSomeId());
AddressEntity offAddressEntity = (AddressEntity) addressService.getOffAddress(customerEntity.getSomeId());
List<KeyContactsEntity> listKeyContacts = keyContactService.getKeyContactOfClient(customerEntity.getSomeId());
List<PropertyEntity> listProperty = propertyService.getListOfProperty(customerEntity.getSomeId()) ;
customerDto = masterService.setEntityValues(customerDto,customerEntity,resAddressEntity,offAddressEntity,listKeyContacts,listProperty);

默认情况下只会使用一个事务。

您可以在此处阅读有关事务传播的内容以充分理解:

Spring transaction propagation

默认情况下 Spring 将使用 "Required" 策略,即 "support current transaction, create a new one if none exists"。还有许多其他策略可以满足您的需求。

一个典型的"gotcha":Spring事务管理是基于代理的,所以它只会在你调用一个方法时触发,该方法位于另一个class而不是调用者,即没有当您在同一 class.

上调用方法时会触发事务

交易的运作方式很简单。如果从一个非事务性的组件控制器调用一个服务的方法,即事务性,您的服务方法创建事务,然后当方法完成时,由于您的控制器不是事务性的,事务完成并且它承诺。

所以在你的情况下,你从一个非事务组件调用所有这些服务,你为它们中的每一个都创建了一个新的事务,这是错误的,因为这意味着如果第三个服务出现问题你无法回滚前两个

class Controller {

    //New transaction
    CustomerEntity customerEntity = (CustomerEntity) customerService.getCustomerFromLeadId(id);
    //New transaction
    AddressEntity resAddressEntity = (AddressEntity) addressService.getResAddress(customerEntity.getSomeId());
    //New transaction
    AddressEntity offAddressEntity = (AddressEntity) addressService.getOffAddress(customerEntity.getSomeId());
    //New transaction / if something goes wrong no rollback for previous transactions
    List<KeyContactsEntity> listKeyContacts = keyContactService.getKeyContactOfClient(customerEntity.getSomeId());

}

如果您希望将所有服务事务集中在一个中,您需要将它们全部包装到一个带有@Transaction

的"facade" 组件中
   @Transactional
   class FacadeService {

    //New transaction
    CustomerEntity customerEntity = (CustomerEntity) customerService.getCustomerFromLeadId(id);
    //Reuse transaction
    AddressEntity resAddressEntity = (AddressEntity) addressService.getResAddress(customerEntity.getSomeId());
    //Reuse transaction
    AddressEntity offAddressEntity = (AddressEntity) addressService.getOffAddress(customerEntity.getSomeId());
    //Reuse transaction / If something goes wrong rollback of everyting
    List<KeyContactsEntity> listKeyContacts = keyContactService.getKeyContactOfClient(customerEntity.getSomeId());

}