Spring多数据源事务处理机制

最近有spring配置多数据源,中间用了aop来完成动态的切换,发现一些地方不是很明白,在AbstractRoutingDataSource这个类中有determineCurrentLookupKey的方法,另外我在所有DAO层方法上添加了before的切面,按理说,如果调用了某一个DAO层的方法,应该是先调用切面的方法,然后再调用determineCurrentLookupKey方法,最后才是DAO层的方法,可是我调试的结果是determineCurrentLookupKey方法,其次切面,最后DAO,不是很理解AbstractRoutingDataSource的调用过程。

原因:当在service层调用dao层进行数据库处理时,若service 没有启动事务机制,则执行的顺序为:切面——>determineCurrentLookupKey——>Dao方法。而当在service层启动事务时,由于在一个事务中执行失败后会回滚之前所执行的所有操作,因此spring会在service方法执行前调用determineCurrentLookupKey,此时无聊service中有多少个dao调用determineCurrentLookupKey将不再执行,即在事务中不支持数据源切换。


如:

@Transactional(propagation = Propagation.REQUIRED) //顺序为:切面——>determineCurrentLookupKey——>Dao方法
public String getJsonList(PageBean page,Map<String,String> map,String className,String order){
List<T> list=new ArrayList<T>();
if(order.equals("null"))
list=getList(page,map,className);
else
list=getList(page,map,className,order);
int rowCount = dao.getCount("select count(*) from "+className+Utils.getHql(map));
HashMap<String, Object> tempMap = new HashMap<String, Object>();
tempMap.put("Rows", list);
tempMap.put("Total", rowCount);
JSONObject json = new JSONObject();
json.putAll(tempMap);
return json.toString();
}


@Transactional(propagation = Propagation.SUPPORTS)//顺序为:determineCurrentLookupKey——>切面——>Dao方法
public String getJsonList(PageBean page,Map<String,String> map,String className,String order){
List<T> list=new ArrayList<T>();
if(order.equals("null"))
list=getList(page,map,className);
else
list=getList(page,map,className,order);
int rowCount = dao.getCount("select count(*) from "+className+Utils.getHql(map));
HashMap<String, Object> tempMap = new HashMap<String, Object>();
tempMap.put("Rows", list);
tempMap.put("Total", rowCount);
JSONObject json = new JSONObject();
json.putAll(tempMap);
return json.toString();
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值