Spring多数据源事务处理机制

来源:互联网 发布:js判断是否为整数数字 编辑:程序博客网 时间:2024/05/20 18:17

最近有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();
}

0 0