Data source switching and transaction failure

Foreword:

    In the process of doing a project, you may need to use multiple databases. Using @DS to switch data sources, you must first figure out the correct way to use the @DS annotation

Open method:

      When the annotation is added to the class, it means that the methods in this class use this data source;
      when the annotation is added to the method, it means that the data source used on this method has priority over all other configurations; 

Error example:

@Service
public class ServiceImpl implements Service{
 
    /**
     * 实现方法A
     * @param 
     * @return
     */
    @Override
    @DS("database1")
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void functionA() {
        ...
        functionB(); //调用B方法且切换为B方法的所需要的数据源
    }
 
    /**
     * 实现方法B
     * @param 
     * @return
     */
    @Override
    @DS("database2")
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void function B() {
 
    }
}

Error: When method A calls method B, the @DS annotation of method B will not take effect and will be completely covered by @DS ("database1) of method A.

Analysis of the cause of the error : The above method is only applicable to the use of different methods and different data sources in the same class, and transactions cannot be used , otherwise the data source will not switch.

———————————————————————————

The correct way to open : call methods in different classes

In particular, it is important to remember to open the transaction

@Service("serviceA")
public class ServiceImplA implements ServiceA{
    @Resource
    ServiceImplB serviceImplB ;
    /**
     * 实现方法A
     * @param 
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @DS("database1")
    public void functionA() {
        ...
        ServiceImplB.functionB(); //调用B类的B方法
    }
}
 
@Service("serviceB")
public class ServiceImplB implements ServiceB{
      /**
     * 实现方法B
     * @param 
     * @return
     */
    @Override
    @DS("database2")
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)  
    public void function B() {
 
    }
}
  

 

 

Guess you like

Origin blog.csdn.net/gracexiao168/article/details/126776435