Example usage for org.apache.ibatis.plugin Invocation getMethod

List of usage examples for org.apache.ibatis.plugin Invocation getMethod

Introduction

In this page you can find the example usage for org.apache.ibatis.plugin Invocation getMethod.

Prototype

public Method getMethod() 

Source Link

Usage

From source file:com.chrhc.mybatis.locker.interceptor.OptimisticLocker.java

License:Apache License

@Override
public Object intercept(Invocation invocation) throws Exception {
    String versionColumn;/*from ww w  .j  a v a2 s. c o m*/
    String versionField;
    if (null == props || props.isEmpty()) {
        versionColumn = "version";
        versionField = "version";
    } else {
        versionColumn = props.getProperty("versionColumn", "version");
        versionField = props.getProperty("versionField", "version");
    }
    String interceptMethod = invocation.getMethod().getName();
    if (!"prepare".equals(interceptMethod)) {
        return invocation.proceed();
    }
    StatementHandler handler = (StatementHandler) PluginUtil.processTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(handler);
    MappedStatement ms = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    SqlCommandType sqlCmdType = ms.getSqlCommandType();
    if (sqlCmdType != SqlCommandType.UPDATE) {
        return invocation.proceed();
    }
    BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
    VersionLocker vl = getVersionLocker(ms, boundSql);
    if (null != vl && !vl.value()) {
        return invocation.proceed();
    }
    Object originalVersion = metaObject.getValue("delegate.boundSql.parameterObject." + versionField);
    if (originalVersion == null || Long.parseLong(originalVersion.toString()) <= 0) {
        throw new BindingException("value of version field[" + versionField + "]can not be empty");
    }
    String originalSql = boundSql.getSql();
    if (log.isDebugEnabled()) {
        log.debug("==> originalSql: " + originalSql);
    }
    originalSql = addVersionToSql(originalSql, versionColumn, originalVersion);
    metaObject.setValue("delegate.boundSql.sql", originalSql);
    if (log.isDebugEnabled()) {
        log.debug("==> originalSql after add version: " + originalSql);
    }
    return invocation.proceed();
}

From source file:com.luxoft.mybatis.splitter.UpdateSplitterPlugin.java

License:Apache License

@Override
public Object intercept(Invocation invocation) throws Throwable {
    MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
    Object parameterObject = invocation.getArgs()[1];
    final Configuration configuration = ms.getConfiguration();
    final StatementHandler handler = configuration.newStatementHandler((Executor) invocation.getTarget(), ms,
            parameterObject, RowBounds.DEFAULT, null, null);
    final BoundSql boundSql = handler.getBoundSql();
    final String sql = boundSql.getSql();
    List<String> splitted = splitter.split(sql);
    int rc = 0;//from   w  ww .ja v  a 2  s  .  c  o  m
    List<ParameterMapping> fullParameterMappings = new ArrayList<ParameterMapping>(
            boundSql.getParameterMappings());
    for (String sqlPart : splitted) {
        if (skipEmptyStatements && sqlPart.length() == 0) {
            continue;
        }
        int numParams = 0;
        for (int index = sqlPart.indexOf('?'); index >= 0; index = sqlPart.indexOf('?', index + 1)) {
            numParams++;
        }
        MappedStatement subStatement = subStatements.get(ms);
        if (subStatement == null) {
            subStatement = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(),
                    new SwitchingSqlSource(configuration), ms.getSqlCommandType()).cache(ms.getCache())
                            .databaseId(ms.getDatabaseId()).fetchSize(ms.getFetchSize())
                            .timeout(ms.getTimeout()).flushCacheRequired(ms.isFlushCacheRequired())
                            .useCache(ms.isUseCache()).build();
            subStatements.put(ms, subStatement);
        }
        List<ParameterMapping> subParameterMappings = fullParameterMappings.subList(0, numParams);
        ((SwitchingSqlSource) subStatement.getSqlSource()).switchParams(sqlPart, boundSql,
                new ArrayList<ParameterMapping>(subParameterMappings));
        subParameterMappings.clear();
        int subRc = (Integer) invocation.getMethod().invoke(invocation.getTarget(), subStatement,
                parameterObject);
        if (rc >= 0) {
            rc = subRc < 0 ? subRc : rc + subRc;
        }
    }
    return rc;
}

From source file:com.mook.locker.interceptor.OptimisticLocker.java

License:Apache License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object intercept(Invocation invocation) throws Exception {

    String interceptMethod = invocation.getMethod().getName();
    String versionColumn = props.getProperty("versionColumn", "version");

    if ("prepare".equals(interceptMethod)) {

        StatementHandler handler = (StatementHandler) invocation.getTarget();
        MetaObject hm = SystemMetaObject.forObject(handler);

        MappedStatement ms = (MappedStatement) hm.getValue("delegate.mappedStatement");
        SqlCommandType sqlCmdType = ms.getSqlCommandType();
        if (sqlCmdType != SqlCommandType.UPDATE) {
            return invocation.proceed();
        }/* w  w  w.j  av a  2 s .  c o m*/

        BoundSql boundSql = (BoundSql) hm.getValue("delegate.boundSql");
        if (hasVersionLocker(ms, boundSql)) {
            return invocation.proceed();
        }

        Object originalVersion = hm.getValue("delegate.boundSql.parameterObject.version");
        Object versionIncr = castTypeAndOptValue(originalVersion,
                hm.getValue("delegate.boundSql.parameterObject"), ValueType.INCREASE);
        hm.setValue("delegate.boundSql.parameterObject.version", versionIncr);

        String originalSql = (String) hm.getValue("delegate.boundSql.sql");
        StringBuilder builder = new StringBuilder(originalSql);
        builder.append(" and ");
        builder.append(versionColumn);
        builder.append(" = ?");
        hm.setValue("delegate.boundSql.sql", builder.toString());

        if (log.isDebugEnabled()) {
            log.debug("==> originalSql: " + originalSql);
        }

        return invocation.proceed();

    } else if ("setParameters".equals(interceptMethod)) {

        ParameterHandler handler = (ParameterHandler) invocation.getTarget();
        MetaObject hm = SystemMetaObject.forObject(handler);

        MappedStatement ms = (MappedStatement) hm.getValue("mappedStatement");
        SqlCommandType sqlCmdType = ms.getSqlCommandType();
        if (sqlCmdType != SqlCommandType.UPDATE) {
            return invocation.proceed();
        }

        Configuration configuration = (Configuration) hm.getValue("configuration");
        BoundSql boundSql = (BoundSql) hm.getValue("boundSql");

        if (hasVersionLocker(ms, boundSql)) {
            return invocation.proceed();
        }

        Object result = invocation.proceed();

        ParameterMapping versionMapping = new ParameterMapping.Builder(configuration, versionColumn,
                Object.class).build();

        Object parameterObject = boundSql.getParameterObject();

        MetaObject pm = configuration.newMetaObject(parameterObject);
        if (parameterObject instanceof MapperMethod.ParamMap<?>) {
            MapperMethod.ParamMap<?> paramMap = (MapperMethod.ParamMap<?>) parameterObject;
            if (!paramMap.containsKey(versionColumn)) {
                throw new TypeException("??MyBatis@Param");
            }
        }
        Object value = pm.getValue(versionColumn);
        TypeHandler typeHandler = versionMapping.getTypeHandler();
        JdbcType jdbcType = versionMapping.getJdbcType();

        if (value == null && jdbcType == null) {
            jdbcType = configuration.getJdbcTypeForNull();
        }
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        try {
            PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];
            Object val = castTypeAndOptValue(value, parameterObject, ValueType.DECREASE);
            typeHandler.setParameter(ps, parameterMappings.size() + 1, val, jdbcType);
        } catch (TypeException e) {
            throw new TypeException(
                    "Could not set parameters for mapping: " + parameterMappings + ". Cause: " + e, e);
        } catch (SQLException e) {
            throw new TypeException(
                    "Could not set parameters for mapping: " + parameterMappings + ". Cause: " + e, e);
        }
        return result;
    }
    return invocation.proceed();
}

From source file:com.navercorp.pinpoint.web.dao.ibatis.BindingLogPlugin32.java

License:Apache License

@Override
public Object intercept(Invocation invocation) throws Throwable {
    if (internalLogger.isTraceEnabled()) {
        internalLogger.trace("target:" + invocation.getTarget() + " method:" + invocation.getMethod() + " args:"
                + Arrays.toString(invocation.getArgs()));
    }/*from w w w .j a v a2s  . c o m*/
    try {
        return invocation.proceed();
    } finally {
        bindingLog(invocation);
    }
}

From source file:com.wbsf.core.mybatis.mook.locker.interceptor.OptimisticLocker.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object intercept(Invocation invocation) throws Exception {

    String versionColumn;//from w  w  w. j a v  a2 s .  c o m
    if (null == props || props.isEmpty()) {
        versionColumn = "version";
    } else {
        versionColumn = props.getProperty("versionColumn", "version");
    }

    String interceptMethod = invocation.getMethod().getName();
    if ("prepare".equals(interceptMethod)) {

        StatementHandler routingHandler = (StatementHandler) PluginUtil.processTarget(invocation.getTarget());
        MetaObject routingMeta = SystemMetaObject.forObject(routingHandler);
        MetaObject hm = routingMeta.metaObjectForProperty("delegate");

        VersionLocker vl = VersionLockerResolver.resolve(hm);
        if (null != vl && !vl.value()) {
            return invocation.proceed();
        }

        String originalSql = (String) hm.getValue("boundSql.sql");
        StringBuilder builder = new StringBuilder(originalSql);
        builder.append(" AND ");
        builder.append(versionColumn);
        builder.append(" = ?");
        hm.setValue("boundSql.sql", builder.toString());

    } else if ("setParameters".equals(interceptMethod)) {

        ParameterHandler handler = (ParameterHandler) PluginUtil.processTarget(invocation.getTarget());
        MetaObject hm = SystemMetaObject.forObject(handler);

        VersionLocker vl = VersionLockerResolver.resolve(hm);
        if (null != vl && !vl.value()) {
            return invocation.proceed();
        }

        BoundSql boundSql = (BoundSql) hm.getValue("boundSql");
        Object parameterObject = boundSql.getParameterObject();
        if (parameterObject instanceof MapperMethod.ParamMap<?>) {
            MapperMethod.ParamMap<?> paramMap = (MapperMethod.ParamMap<?>) parameterObject;
            if (!paramMap.containsKey(versionColumn)) {
                throw new TypeException(
                        "All the primitive type parameters must add MyBatis's @Param Annotaion");
            }
        }

        Configuration configuration = ((MappedStatement) hm.getValue("mappedStatement")).getConfiguration();
        MetaObject pm = configuration.newMetaObject(parameterObject);
        Object value = pm.getValue(versionColumn);
        ParameterMapping versionMapping = new ParameterMapping.Builder(configuration, versionColumn,
                Object.class).build();
        TypeHandler typeHandler = versionMapping.getTypeHandler();
        JdbcType jdbcType = versionMapping.getJdbcType();

        if (value == null && jdbcType == null) {
            jdbcType = configuration.getJdbcTypeForNull();
        }

        int versionLocation = boundSql.getParameterMappings().size() + 1;
        try {
            PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];
            typeHandler.setParameter(ps, versionLocation, value, jdbcType);
        } catch (TypeException | SQLException e) {
            throw new TypeException("set parameter 'version' faild, Cause: " + e, e);
        }

        if (value.getClass() != Long.class && value.getClass() != long.class) {
            if (log.isDebugEnabled()) {
                log.error(Constent.LogPrefix
                        + "property type error, the type of version property must be Long or long.");
            }
        }

        // increase version
        pm.setValue(versionColumn, (long) value + 1);
    }
    return invocation.proceed();
}

From source file:org.apache.aurora.scheduler.storage.db.InstrumentingInterceptor.java

License:Apache License

private String generateStatsName(Invocation invocation) {
    if (firstArgumentIsMappedStatement(invocation)) {
        MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
        return statement.getId();
    }/*from  w ww . j  a v  a  2  s  .  com*/

    LOG.warn(
            "Received invocation for unknown or invalid target. Invocation target: {}. "
                    + "Invocation method: {}. Using metric name '{}' instead.",
            invocation.getTarget(), invocation.getMethod(), INVALID_INVOCATION_METRIC_NAME);
    return INVALID_INVOCATION_METRIC_NAME;
}

From source file:org.mybatis.spring.ExecutorInterceptor.java

License:Apache License

public Object intercept(Invocation invocation) throws Throwable {
    if ("commit".equals(invocation.getMethod().getName())) {
        ++this.commitCount;
    } else if ("rollback".equals(invocation.getMethod().getName())) {
        ++this.rollbackCount;
    } else if ("close".equals(invocation.getMethod().getName())) {
        this.closed = true;
    }//from  w ww  .ja  v  a 2  s . c  om

    return invocation.proceed();
}

From source file:org.njqspringboot.support.mybatis.locker.interceptor.OptimisticLocker.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object intercept(Invocation invocation) throws Exception {

    String versionColumn;/*from  w  w w.  j  ava 2s.c  o  m*/
    if (null == props || props.isEmpty()) {
        versionColumn = "version";
    } else {
        versionColumn = props.getProperty("versionColumn", "version");
    }

    String interceptMethod = invocation.getMethod().getName();
    if ("prepare".equals(interceptMethod)) {

        StatementHandler handler = (StatementHandler) PluginUtil.processTarget(invocation.getTarget());
        MetaObject hm = SystemMetaObject.forObject(handler);

        MappedStatement ms = (MappedStatement) hm.getValue("delegate.mappedStatement");
        SqlCommandType sqlCmdType = ms.getSqlCommandType();
        if (sqlCmdType != SqlCommandType.UPDATE) {
            return invocation.proceed();
        }

        BoundSql boundSql = (BoundSql) hm.getValue("delegate.boundSql");

        VersionLocker vl = getVersionLocker(ms, boundSql);
        if (null != vl && !vl.value()) {
            return invocation.proceed();
        }

        Object originalVersion = hm.getValue("delegate.boundSql.parameterObject." + versionColumn);
        Object versionIncr = castTypeAndOptValue(originalVersion,
                hm.getValue("delegate.boundSql.parameterObject"), ValueType.INCREASE);
        hm.setValue("delegate.boundSql.parameterObject." + versionColumn, versionIncr);

        String originalSql = (String) hm.getValue("delegate.boundSql.sql");
        StringBuilder builder = new StringBuilder(originalSql);
        builder.append(" and ");
        builder.append(versionColumn);
        builder.append(" = ?");
        hm.setValue("delegate.boundSql.sql", builder.toString());

        if (log.isDebugEnabled()) {
            log.debug("==> originalSql: " + originalSql);
        }

        return invocation.proceed();

    } else if ("setParameters".equals(interceptMethod)) {

        ParameterHandler handler = (ParameterHandler) PluginUtil.processTarget(invocation.getTarget());
        MetaObject hm = SystemMetaObject.forObject(handler);

        MappedStatement ms = (MappedStatement) hm.getValue("mappedStatement");
        SqlCommandType sqlCmdType = ms.getSqlCommandType();
        if (sqlCmdType != SqlCommandType.UPDATE) {
            return invocation.proceed();
        }

        Configuration configuration = ms.getConfiguration();
        BoundSql boundSql = (BoundSql) hm.getValue("boundSql");

        VersionLocker vl = getVersionLocker(ms, boundSql);
        if (null != vl && !vl.value()) {
            return invocation.proceed();
        }

        Object result = invocation.proceed();

        ParameterMapping versionMapping = new ParameterMapping.Builder(configuration, versionColumn,
                Object.class).build();

        Object parameterObject = boundSql.getParameterObject();

        MetaObject pm = configuration.newMetaObject(parameterObject);
        if (parameterObject instanceof MapperMethod.ParamMap<?>) {
            MapperMethod.ParamMap<?> paramMap = (MapperMethod.ParamMap<?>) parameterObject;
            if (!paramMap.containsKey(versionColumn)) {
                throw new TypeException("All the base type parameters must add MyBatis's @Param Annotaion");
            }
        }
        Object value = pm.getValue(versionColumn);
        TypeHandler typeHandler = versionMapping.getTypeHandler();
        JdbcType jdbcType = versionMapping.getJdbcType();

        if (value == null && jdbcType == null) {
            jdbcType = configuration.getJdbcTypeForNull();
        }
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        try {
            PreparedStatement ps = (PreparedStatement) invocation.getArgs()[0];
            Object val = castTypeAndOptValue(value, parameterObject, ValueType.DECREASE);
            typeHandler.setParameter(ps, parameterMappings.size() + 1, val, jdbcType);
        } catch (TypeException e) {
            throw new TypeException(
                    "Could not set parameters for mapping: " + parameterMappings + ". Cause: " + e, e);
        } catch (SQLException e) {
            throw new TypeException(
                    "Could not set parameters for mapping: " + parameterMappings + ". Cause: " + e, e);
        }
        return result;
    }
    return invocation.proceed();
}