Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Advanced Techniques for MyBatis Interceptors in Data Operations

Tech 1

Intercepting Insert Operations

A common use case involves inserting data into multiple rows simultaneously during a single operation. For instance, a pllatform administrator might need to replicate data across different country-specific records.

Implementation:

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Constructor;
import java.util.List;

@Slf4j
@Component
@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class MultiInsertInterceptor implements Interceptor {

    @Value("${config.tables.with-country}")
    private String countryEnabledTables;
    @Resource
    private UserService userService;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!userService.hasAdminRole()) {
            return invocation.proceed();
        }

        Object[] parameters = invocation.getArgs();
        MappedStatement statement = (MappedStatement) parameters[0];

        if (statement.getSqlCommandType() == SqlCommandType.INSERT) {
            Object paramObj = parameters[1];
            Class<?> paramClass = paramObj.getClass();
            TableName tableAnnotation = paramClass.getAnnotation(TableName.class);
            String tableName = tableAnnotation.value();
            if (!countryEnabledTables.contains(tableName)) {
                return invocation.proceed();
            }
            CountryDataEntity originalEntity = (CountryDataEntity) parameters[1];
            originalEntity.setCountryCode(userService.getUserCountryCode());
            originalEntity.setIdentifier(CodeGenerator.createUniqueCode());
            Constructor<?> constructor = paramClass.getConstructor();
            CountryDataEntity newEntity;
            List<String> countryCodes = userService.getUserCountryCodes();
            for (String code : countryCodes) {
                newEntity = (CountryDataEntity) constructor.newInstance();
                BeanUtils.copyProperties(originalEntity, newEntity);
                newEntity.setCountryCode(code);
                Executor executor = (Executor) invocation.getTarget();
                executor.update(statement, newEntity);
            }
        }
        return invocation.proceed();
    }
}

Some entity classes may require custom instantiation.

Intercepting Update Operations

When updating data, it might be necessary to modify related rows in other tables concurrently.

Intercepting Query Operations

Query operations can be enhanced by automatically appending specific conditions, such as filtering by country.

Implementation:

@Slf4j
@Component
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class QueryModifierInterceptor implements Interceptor {
    private static final String COUNTRY_CODE_FIELD = "country_code";

    @Value("${config.tables.with-country}")
    private String countryEnabledTables;

    @Resource
    private UserService userService;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!userService.hasAdminRole()) {
            return invocation.proceed();
        }

        RoutingStatementHandler routingHandler = (RoutingStatementHandler) invocation.getTarget();
        StatementHandler delegateHandler = (StatementHandler) ReflectionHelper.getFieldValue(routingHandler, "delegate");
        BoundSql boundSql = delegateHandler.getBoundSql();
        String sqlText = boundSql.getSql();
        Statement parsedStatement = CCJSqlParserUtil.parse(sqlText);

        MappedStatement mappedStmt = (MappedStatement) ReflectionHelper.getFieldValue(delegateHandler, "mappedStatement");
        SqlCommandType cmdType = mappedStmt.getSqlCommandType();
        if (SqlCommandType.SELECT.equals(cmdType)) {
            Select selectStmt = (Select) parsedStatement;
            PlainSelect selectBody = (PlainSelect) selectStmt.getSelectBody();
            Table sourceTable = (Table) selectBody.getFromItem();
            String tableName = sourceTable.getName();
            if (!countryEnabledTables.contains(tableName)) {
                return invocation.proceed();
            }
            addFilterCondition(selectBody);
            ReflectionHelper.setFieldValue(boundSql, "sql", parsedStatement.toString());
        } else if (SqlCommandType.UPDATE.equals(cmdType)) {
            String additionalClause = " or id in(" + userService.getTargetIds() + ")";
            sqlText = sqlText + additionalClause;
            ReflectionHelper.setFieldValue(boundSql, "sql", sqlText);
        }
        return invocation.proceed();
    }

    private void addFilterCondition(PlainSelect selectBody) {
        try {
            String whereExpression;
            try {
                EqualsTo whereClause = (EqualsTo) selectBody.getWhere();
                whereExpression = whereClause.getStringExpression();
            } catch (Exception e) {
                whereExpression = selectBody.getWhere().toString();
            }
            StringBuilder filterBuilder = new StringBuilder(128);
            if (!whereExpression.contains(COUNTRY_CODE_FIELD)) {
                filterBuilder.append("(country_code in ( ").append(userService.getTargetIds()).append(")) ");
                constructWhereClause(selectBody, filterBuilder.toString());
            }
        } catch (Exception e) {
            log.error("Error adding condition", e);
        }
    }

    private void constructWhereClause(PlainSelect select, String filterClause) throws JSQLParserException {
        if (select.getWhere() == null) {
            select.setWhere(CCJSqlParserUtil.parseCondExpression(filterClause));
        } else {
            AndExpression combined = new AndExpression(
                CCJSqlParserUtil.parseCondExpression(filterClause), select.getWhere());
            select.setWhere(combined);
        }
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.