Java Code Examples for org.apache.ibatis.mapping.MappedStatement#getBoundSql()

The following examples show how to use org.apache.ibatis.mapping.MappedStatement#getBoundSql() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseStatementHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
  this.configuration = mappedStatement.getConfiguration();
  this.executor = executor;
  this.mappedStatement = mappedStatement;
  this.rowBounds = rowBounds;

  this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  this.objectFactory = configuration.getObjectFactory();

  if (boundSql == null) { // issue #435, get the key before calculating the statement
    generateKeys(parameterObject);
    boundSql = mappedStatement.getBoundSql(parameterObject);
  }

  this.boundSql = boundSql;

  //生成parameterHandler
  this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
  //生成resultSetHandler
  this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
}
 
Example 2
Source File: BaseStatementHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
protected BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
  this.configuration = mappedStatement.getConfiguration();
  this.executor = executor;
  this.mappedStatement = mappedStatement;
  this.rowBounds = rowBounds;

  this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
  this.objectFactory = configuration.getObjectFactory();

  if (boundSql == null) { // issue #435, get the key before calculating the statement
    generateKeys(parameterObject);
    boundSql = mappedStatement.getBoundSql(parameterObject);
  }

  this.boundSql = boundSql;

  //生成parameterHandler
  this.parameterHandler = configuration.newParameterHandler(mappedStatement, parameterObject, boundSql);
  //生成resultSetHandler
  this.resultSetHandler = configuration.newResultSetHandler(executor, mappedStatement, rowBounds, parameterHandler, resultHandler, boundSql);
}
 
Example 3
Source File: CheckSQLInterceptor.java    From java-tutorial with MIT License 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

    //获取方法的第0个参数,也就是MappedStatement。@Signature注解中的args中的顺序
    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    //获取sql命令操作类型
    SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
    final Object[] queryArgs = invocation.getArgs();
    final Object parameter = queryArgs[1];

    BoundSql boundSql = mappedStatement.getBoundSql(parameter);
    String sql = boundSql.getSql();

    if (SqlCommandType.DELETE.equals(sqlCommandType)) {
        //格式化sql
        sql = sql.replace("\n", "");
        if (!sql.toLowerCase().contains(SQL_DELETE_WHERE)) {
            sql = sql.replace(" ", "");
            logger.warn("删除语句中没有where条件,sql为:{}", sql);
            throw new SQLException("删除语句中没有where条件");
        }
        return invocation.proceed();
    }

    return null;
}
 
Example 4
Source File: SortListInterceptor.java    From QuickProject with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
       List<Sort> sortList = getSortList();
       if (sortList == null || sortList.size() == 0) {
           return invocation.proceed();
       }

       Executor executor = (Executor) invocation.getTarget();
       Object[] args = invocation.getArgs();
       MappedStatement ms = (MappedStatement) args[0];
       Object parameter = args[1];
       RowBounds rowBounds = (RowBounds) args[2];
       ResultHandler resultHandler = (ResultHandler) args[3];

       // 计算修改BoundSql
       BoundSql boundSql = ms.getBoundSql(parameter);
       MetaObject boundSqlHandler = MetaObject.forObject(boundSql, new DefaultObjectFactory(), new DefaultObjectWrapperFactory());
       Dialect dialect = DialectParser.parse(ms.getConfiguration());
       String sql = (String) boundSqlHandler.getValue("sql");
       sql = dialect.addSortString(sql, sortList);
       boundSqlHandler.setValue("sql", sql);

       // 继续执行原来的代码
       CacheKey key = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
       return executor.query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
 
Example 5
Source File: PageInterceptor.java    From Zebra with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object[] args = invocation.getArgs();
	Object rowBound = args[2];

	MappedStatement ms = (MappedStatement) args[0];
	if (rowBound != null) {
		RowBounds rb = (RowBounds) rowBound;

		// without pagination
		if (rb.getOffset() == RowBounds.NO_ROW_OFFSET && rb.getLimit() == RowBounds.NO_ROW_LIMIT) {
			return invocation.proceed();
		} else {
			BoundSql boundSql = ms.getBoundSql(args[1]);

			if (rowBound instanceof PageModel) {
				// physical pagination with PageModel
				PageModel pageModel = (PageModel) rowBound;
				Object count = queryCount(invocation, args, ms, boundSql);
				Object records = queryLimit(invocation, args, ms, boundSql, pageModel);

				pageModel.setRecordCount((Integer) ((List<?>) count).get(0));
				pageModel.setRecords((List<?>) records);

				return null;
			} else {
				// physical pagination with RowBounds
				return queryLimit(invocation, args, ms, boundSql, rb);
			}
		}
	} else {
		// without pagination
		return invocation.proceed();
	}
}
 
Example 6
Source File: PaginationPlugin.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
private InvocationContext processIntercept(InvocationContext context)throws Throwable {
	MappedStatement ms = context.getMappedStatement();
	Pagination pagination = context.getPagination();
	
	
	BoundSql boundSql = ms.getBoundSql(pagination.getCriteria());
	
	// counting
	if(pagination.isNeedTotalCount()){
		Integer counting = new CountingExecutor(ms, dialect, boundSql).execute();
		pagination.setTotalCount(counting);
	}
	// paging
	String pagingSql = dialect.getPagingSQL(boundSql.getSql().trim());
	
	// cpy mappings
	List<ParameterMapping> mappings = new ArrayList<ParameterMapping>();
	if(boundSql.getParameterMappings() != null){
		List<ParameterMapping> tmpMappings = boundSql.getParameterMappings();
		for (int i = 0; i < tmpMappings.size(); i++) {
			mappings.add(tmpMappings.get(i));
		}
	}
	
	BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), pagingSql, mappings, boundSql.getParameterObject());
	cpyAndAppendParameters(ms, pagination, boundSql, newBoundSql);
	
	InvocationContext newContext = new InvocationContext();
       MappedStatement newms = cloneMappedStatement(ms, newBoundSql);
       newContext.setMappedStatement(newms);
       newContext.setPagination(pagination);
       
       return newContext;
}
 
Example 7
Source File: PagePluging.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
void processIntercept(final Object[] queryArgs) {
	MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
	Object parameter = queryArgs[PARAMETER_INDEX];
	final RowBounds rowBounds = (RowBounds) queryArgs[ROWBOUNDS_INDEX];
	int offset = rowBounds.getOffset();
	int limit = rowBounds.getLimit();
	if (dialect.supportsLimit() && (offset != RowBounds.NO_ROW_OFFSET || limit != RowBounds.NO_ROW_LIMIT)) {
		BoundSql boundSql = ms.getBoundSql(parameter);
		String sql = boundSql.getSql().trim();
		if (dialect.supportsLimitOffset()) {
			sql = dialect.getLimitString(sql, offset, limit);
			offset = RowBounds.NO_ROW_OFFSET;
		} else {
			sql = dialect.getLimitString(sql, 0, limit);
		}
		limit = RowBounds.NO_ROW_LIMIT;
		queryArgs[ROWBOUNDS_INDEX] = new RowBounds(offset, limit);
		BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(),
				boundSql.getParameterObject());
		for (ParameterMapping mapping : boundSql.getParameterMappings()) {
			String prop = mapping.getProperty();
			if (boundSql.hasAdditionalParameter(prop)) {
				newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
			}
		}
		MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
		queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
	}
}
 
Example 8
Source File: SqlLogInterceptor.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * Intercept object.
 *
 * @param invocation the invocation
 *
 * @return the object
 *
 * @throws Throwable the throwable
 */
@Override
public Object intercept(Invocation invocation) throws Throwable {
	long start = System.currentTimeMillis();

	MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
	Object parameter = null;
	if (invocation.getArgs().length > 1) {
		parameter = invocation.getArgs()[1];
	}
	BoundSql boundSql = mappedStatement.getBoundSql(parameter);
	Configuration configuration = mappedStatement.getConfiguration();
	String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
	List<String> paramList = getParamList(configuration, boundSql);
	Object proceed = invocation.proceed();
	int result = 0;
	if (proceed instanceof ArrayList) {
		ArrayList resultList = (ArrayList) proceed;
		result = resultList.size();
	}
	if (proceed instanceof Integer) {
		result = (Integer) proceed;
	}
	if (enableSqlLogInterceptor) {
		long end = System.currentTimeMillis();
		long time = end - start;
		Boolean flag = (Boolean) ThreadLocalMap.get(NotDisplaySqlAspect.DISPLAY_SQL);
		if (time >= noticeTime * GlobalConstant.Number.THOUSAND_INT) {
			log.error("执行超过{}秒,sql={}", noticeTime, sql);
			log.error("result={}, time={}ms, params={}", result, time, paramList);
			return proceed;
		}
		if (flag == null || Objects.equals(flag, true)) {
			log.info("sql={}", sql);
			log.info("result={},time={}ms, params={}", result, time, paramList);
		}
	}
	return proceed;
}
 
Example 9
Source File: MybatisInterceptor.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public Object intercept(Invocation invocation) throws Throwable {
    Object returnValue;
    if (showDetailSql || showCostTime) {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        String sqlId = mappedStatement.getId();
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Configuration configuration = mappedStatement.getConfiguration();

        long start = System.currentTimeMillis();
        returnValue = invocation.proceed();
        long end = System.currentTimeMillis();
        long time = (end - start);

        String sql = getSql(configuration, boundSql, sqlId, time);
        if (slowSqlMs != 0 && time > slowSqlMs) {
            log.warn(sql);
        } else {
            log.info(sql);
        }
    } else {
        returnValue = invocation.proceed();
    }
    return returnValue;
}
 
Example 10
Source File: CachingExecutor.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
 public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
   BoundSql boundSql = ms.getBoundSql(parameterObject);
//query时传入一个cachekey参数
   CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
   return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
 }
 
Example 11
Source File: BaseExecutor.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
 public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
   //得到绑定sql
   BoundSql boundSql = ms.getBoundSql(parameter);
   //创建缓存Key
   CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
   //查询
   return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
 
Example 12
Source File: MybatisSqlInterceptor.java    From taoshop with Apache License 2.0 5 votes vote down vote up
/**
 * 获取sql语句
 * @param invocation
 * @return
 */
private String getSqlByInvocation(Invocation invocation) {
    final Object[] args = invocation.getArgs();
    MappedStatement ms = (MappedStatement) args[0];
    Object parameterObject = args[1];
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    return boundSql.getSql();
}
 
Example 13
Source File: MybatisSqlInterceptor.java    From taoshop with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    // 拦截sql
    Object[] args = invocation.getArgs();
    MappedStatement statement = (MappedStatement) args[0];
    Object parameterObject = args[1];
    BoundSql boundSql = statement.getBoundSql(parameterObject);
    String sql = boundSql.getSql();
    LOGGER.info("获取到的SQL:{}"+sql);
    if (StringUtils.isBlank(sql)) {
        return invocation.proceed();
    }
    // 返回
    return invocation.proceed();
}
 
Example 14
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private Object getNestedQueryConstructorValue(ResultSet rs, ResultMapping constructorMapping, String columnPrefix) throws SQLException {
  final String nestedQueryId = constructorMapping.getNestedQueryId();
  final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId);
  final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType();
  final Object nestedQueryParameterObject = prepareParameterForNestedQuery(rs, constructorMapping, nestedQueryParameterType, columnPrefix);
  Object value = null;
  if (nestedQueryParameterObject != null) {
    final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject);
    final CacheKey key = executor.createCacheKey(nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT, nestedBoundSql);
    final Class<?> targetType = constructorMapping.getJavaType();
    final ResultLoader resultLoader = new ResultLoader(configuration, executor, nestedQuery, nestedQueryParameterObject, targetType, key, nestedBoundSql);
    value = resultLoader.loadResult();
  }
  return value;
}
 
Example 15
Source File: MyBatisCatPlugin.java    From javabase with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	Object result = null;
	Transaction transaction = null;
	MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
	Object objects = (Object)invocation.getArgs()[1];
	BoundSql boundSql = mappedStatement.getBoundSql(objects);
	// 得到 类名-方法
	String[] strArr = mappedStatement.getId().split("\\.");
	String class_method = strArr[strArr.length - 2] + "." + strArr[strArr.length - 1];
	String sql = getSql(mappedStatement.getConfiguration(), boundSql);
	try {
		transaction = Cat.getProducer().newTransaction("SQL", class_method);
		result = invocation.proceed();
		Cat.getProducer().logEvent("SQL.Method", mappedStatement.getSqlCommandType().name(), Message.SUCCESS, "");
		// Cat.getProducer().logEvent("SQL.Database","" ,Message.SUCCESS,"");
		Cat.getProducer().logEvent("SQL.Statement", sql.substring(0, sql.indexOf(" ")), Message.SUCCESS, sql);
		transaction.setStatus(Message.SUCCESS);
	} catch (InvocationTargetException | IllegalAccessException e) {
		transaction.setStatus( ((InvocationTargetException)e).getTargetException().toString());
		log.error( ((InvocationTargetException)e).getTargetException().toString());
		Cat.getProducer().logError( ((InvocationTargetException)e).getTargetException().toString(), e);
		throw e;
	} finally {
		// transaction.addData(boundSql.getSql().trim().replaceAll("\\n",""));
		transaction.complete();
	}
	return result;
}
 
Example 16
Source File: MyBatisSqlUpdateSqlDebugPlugin.java    From smart-admin with MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    Object parameter = invocation.getArgs()[1];
    BoundSql boundSql = mappedStatement.getBoundSql(parameter);
    log.info(boundSql.getSql()+"\r\n"+boundSql.getParameterMappings().toString());
    Object obj = invocation.proceed();
    return obj;
}
 
Example 17
Source File: CachingExecutor.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
 public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
   BoundSql boundSql = ms.getBoundSql(parameterObject);
//query时传入一个cachekey参数
   CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
   return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
 }
 
Example 18
Source File: OffsetLimitInterceptor.java    From AsuraFramework with Apache License 2.0 4 votes vote down vote up
public Object intercept(final Invocation invocation) throws Throwable {
       final Executor executor = (Executor) invocation.getTarget();
       final Object[] queryArgs = invocation.getArgs();
       final MappedStatement ms = (MappedStatement)queryArgs[MAPPED_STATEMENT_INDEX];
       final Object parameter = queryArgs[PARAMETER_INDEX];
       final RowBounds rowBounds = (RowBounds)queryArgs[ROWBOUNDS_INDEX];
       final PageBounds pageBounds = new PageBounds(rowBounds);

       if(pageBounds.getOffset() == RowBounds.NO_ROW_OFFSET
               && pageBounds.getLimit() == RowBounds.NO_ROW_LIMIT
               && pageBounds.getOrders().isEmpty()){
           return invocation.proceed();
       }

       final Dialect dialect;
       try {
           Class clazz = Class.forName(dialectClass);
           Constructor constructor = clazz.getConstructor(MappedStatement.class, Object.class, PageBounds.class);
           dialect = (Dialect)constructor.newInstance(new Object[]{ms, parameter, pageBounds});
       } catch (Exception e) {
           throw new ClassNotFoundException("Cannot create dialect instance: "+dialectClass,e);
       }

       final BoundSql boundSql = ms.getBoundSql(parameter);

       queryArgs[MAPPED_STATEMENT_INDEX] = copyFromNewSql(ms,boundSql,dialect.getPageSQL(), dialect.getParameterMappings(), dialect.getParameterObject());
       queryArgs[PARAMETER_INDEX] = dialect.getParameterObject();
       queryArgs[ROWBOUNDS_INDEX] = new RowBounds(RowBounds.NO_ROW_OFFSET,RowBounds.NO_ROW_LIMIT);

       Boolean async = pageBounds.getAsyncTotalCount() == null ? asyncTotalCount : pageBounds.getAsyncTotalCount();
       Future<List> listFuture = call(new Callable<List>() {
           public List call() throws Exception {
               return (List)invocation.proceed();
           }
       }, async);


       if(pageBounds.isContainsTotalCount()){
           Callable<Paginator> countTask = new Callable() {
               public Object call() throws Exception {
                   Integer count;
                   Cache cache = ms.getCache();
                   if(cache != null && ms.isUseCache() && ms.getConfiguration().isCacheEnabled()){
                       CacheKey cacheKey = executor.createCacheKey(ms,parameter,new PageBounds(),copyFromBoundSql(ms,boundSql,dialect.getCountSQL(), boundSql.getParameterMappings(), boundSql.getParameterObject()));
                       count = (Integer)cache.getObject(cacheKey);
                       if(count == null){
                           count = SQLHelp.getCount(ms,executor.getTransaction(),parameter,boundSql,dialect);
                           cache.putObject(cacheKey, count);
                       }
                   }else{
                       count = SQLHelp.getCount(ms,executor.getTransaction(),parameter,boundSql,dialect);
                   }
                   return new Paginator(pageBounds.getPage(), pageBounds.getLimit(), count);
               }
           };
           Future<Paginator> countFutrue = call(countTask, async);
           return new PageList(listFuture.get(),countFutrue.get());
       }

       return listFuture.get();
}
 
Example 19
Source File: CatMybatisPlugin.java    From pmq with Apache License 2.0 4 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	String sql = "";
	String classMethod = "Notsupported Class Method";
	if (soaConfig.getCatSql() == 1) {
		try {
			//String jdbcUrl = "Notsupported Url";
			//String method = "Notsupported Method";

			// DataSource ds = null;
			MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
			// ds =
			// mappedStatement.getConfiguration().getEnvironment().getDataSource();
			// if (ds instanceof com.mchange.v2.c3p0.ComboPooledDataSource)
			// {
			// com.mchange.v2.c3p0.ComboPooledDataSource c3p0Ds =
			// (com.mchange.v2.c3p0.ComboPooledDataSource) ds;
			// jdbcUrl = c3p0Ds.getJdbcUrl();
			// } else if (ds instanceof
			// org.apache.tomcat.jdbc.pool.DataSource)
			// {
			// org.apache.tomcat.jdbc.pool.DataSource tDs =
			// (org.apache.tomcat.jdbc.pool.DataSource) ds;
			// jdbcUrl = tDs.getUrl();
			// } else if (ds instanceof
			// com.alibaba.druid.pool.DruidDataSource)
			// {
			// @SuppressWarnings("resource")
			// com.alibaba.druid.pool.DruidDataSource dDs =
			// (com.alibaba.druid.pool.DruidDataSource) ds;
			// jdbcUrl = dDs.getUrl();
			// } else if (ds instanceof DynamicDataSource) {
			// com.alibaba.druid.pool.DruidDataSource dDs =
			// (com.alibaba.druid.pool.DruidDataSource) ((DynamicDataSource)
			// ds)
			// .getDataSource();
			// jdbcUrl = dDs.getUrl();
			// } else {
			// jdbcUrl = dbUrl;
			// }

			// 得到 类名-方法
			String[] strArr = mappedStatement.getId().split("\\.");
			classMethod = strArr[strArr.length - 2] + "." + strArr[strArr.length - 1];
			// 得到sql语句
			Object parameter = null;
			if (invocation.getArgs().length > 1) {
				parameter = invocation.getArgs()[1];
			}

			BoundSql boundSql = mappedStatement.getBoundSql(parameter);
			Configuration configuration = mappedStatement.getConfiguration();
			sql = showSql(configuration, boundSql);
			if(classMethod.equals(soaConfig.getCatSqlKey())){
				log.info("the sql is:"+sql);
			}
			

		} catch (Exception ex) {

		}
	}
	Transaction t = null;
	if (soaConfig.getCatSql() == 1) {
		t = Tracer.newTransaction("SQL", classMethod);
	}
	// method = sql.substring(0, sql.indexOf(" "));
	// Tracer.logEvent("SQL.Method", method);
	// Tracer.logEvent("SQL.Database", jdbcUrl);
	// Tracer.logEvent("SQL.Statement", method, Transaction.SUCCESS,
	// sql.length() > 1000 ? sql.substring(0, 1000) : sql);

	Object returnObj = null;
	try {
		returnObj = invocation.proceed();
		if (t != null) {
			t.setStatus(Transaction.SUCCESS);
		}
	} catch (Exception e) {
		if (t != null) {
			t.addData("sql", sql);
			t.setStatus(e);
		}
		throw e;
	} finally {
		if (t != null) {
			t.complete();
		}
	}
	return returnObj;
}
 
Example 20
Source File: DatabaseRouteHandler.java    From azeroth with Apache License 2.0 4 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {

    Object[] objects = invocation.getArgs();
    MappedStatement ms = (MappedStatement) objects[0];
    Object parameterObject = objects[1];

    // TypeHandlerRegistry typeHandlerRegistry =
    // ms.getConfiguration().getTypeHandlerRegistry();

    if (ignoreMappedStatementIds.contains(ms.getId())) {
        return null;
    }
    String namespace = ms.getId().substring(0, ms.getId().lastIndexOf(SPIT_POINT));
    //策略配置忽略
    if (ignoreTablesMapperNameSpace.contains(namespace)) {
        return null;
    }

    BoundSql boundSql = ms.getBoundSql(parameterObject);

    Object parameterObject2 = boundSql.getParameterObject();
    System.out.println(parameterObject2);

    //是否需要分库
    boolean requiredShard = isRequiredShard(boundSql.getSql(), ms.getSqlCommandType(),
            namespace);

    if (requiredShard) {
        //先检查是否已经设置
        Object shardFieldValue = getShardFieldValue(ms.getId(), parameterObject);
        if (shardFieldValue == null) {
            logger.error("方法{}无法获取分库字段{}的值", ms.getId(), shardStrategy.shardEntityField());
        } else {
            int dbIndex = shardStrategy.assigned(shardFieldValue);
            //指定数据库分库序列
            DataSourceContextHolder.get().setDbIndex(dbIndex);
        }
    }
    return null;
}