问题
问题就是使用了transitional注解之后会让DS注解失效。
解决办法
业务逻辑主入口这里正常使用@Transactional注解。
java
package org.springblade.wlw.service.impl;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springblade.wlw.pojo.entity.waterdata.WaterDevice;
import org.springblade.wlw.pojo.entity.waterdata.WaterDistanceDeviceEx;
import org.springblade.wlw.pojo.vo.WaterDistanceDevice;
import org.springblade.wlw.service.IWaterDeviceService;
import org.springblade.wlw.service.IWaterDistanceDeviceExService;
import org.springblade.wlw.service.IWaterDistanceDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class WaterDistanceDeviceServiceImpl implements IWaterDistanceDeviceService {
@Autowired
private IWaterDeviceService waterDeviceService;
@Autowired
private IWaterDistanceDeviceExService waterDistanceDeviceExService;
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void insertFullRecored(WaterDistanceDevice waterDistanceDevice) {
WaterDevice waterDevice = WaterDevice.fromWaterDistanceDevice(waterDistanceDevice);
WaterDistanceDeviceEx deviceEx = WaterDistanceDeviceEx.fromWaterDistanceDevice(waterDistanceDevice);
if (waterDevice == null || deviceEx == null) {
return;
}
waterDeviceService.insertFullRecored(waterDevice);
waterDistanceDeviceExService.insertFullRecored(deviceEx);
}
}
两个单独的service也要声明事务,不过要指定为Propagation.REQUIRED_NEW
. 每个Service上面要通过@DS
注解指定数据源(这是一个正常的操作). 个人的一个建议:DS注解要么全部声明在service类上面, 要么全部生命在mapper接口上面, 避免到处都是。 虽然DS可以声明在方法上面, 但是还是避免吧,最好就是一个service控制一张表,是对一个表的增删改查, 没有必要声明在方法上面。
java
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void insertFullRecored(WaterDevice device) {
this.waterDeviceMapper.insertFullRecord(device);
}
java
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void insertFullRecored(WaterDistanceDeviceEx deviceEx) {
this.waterDistanceDeviceExMapper.insertFullRecord(deviceEx);
}
参考
[1] https://blog.csdn.net/qq_16159433/article/details/120951554