mybatis / mybatis-3

MyBatis SQL mapper framework for Java
http://mybatis.github.io/mybatis-3/
Apache License 2.0
19.72k stars 12.82k forks source link

fix parameter logging issue #3110

Closed qiaomengnan16 closed 6 months ago

qiaomengnan16 commented 6 months ago

MyBatis version

3.5.15

Database vendor and version

MYSQL 5.7.36

Test case or example project

This is the project link: https://github.com/qiaomengnan16/mybatis-log-bug

public class Blog {

    private Integer id;

    private String name;
    // ... getter/setter
}
public interface BlogMapper {
    List<Blog> selectBlog(Integer id);
}
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})})
public class ParamInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        if (target != null && target instanceof StatementHandler) {
            StatementHandler statementHandler = (StatementHandler) target;
            statementHandler.getParameterHandler().setParameters((PreparedStatement) invocation.getArgs()[0]);
            statementHandler.getParameterHandler().setParameters((PreparedStatement) invocation.getArgs()[0]);
            statementHandler.getParameterHandler().setParameters((PreparedStatement) invocation.getArgs()[0]);
        }
        return invocation.proceed();
    }
}
public static void main(String[] args) throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession session = sqlSessionFactory.openSession();
    BlogMapper blogMapper = session.getMapper(BlogMapper.class);
    System.out.println(blogMapper.selectBlog(1));
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.BlogMapper">
    <select id="selectBlog" resultType="org.example.domain.Blog">
        select * from Blog where id = #{id}
    </select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration>
<configuration>

    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%5level [%thread] - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="org.example.mapper.BlogMapper">
        <level value="debug"/>
    </logger>

    <root level="debug">
        <appender-ref ref="stdout"/>
    </root>

</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="SLF4J"/>
    </settings>
    <plugins>
        <plugin interceptor="org.example.interceptor.ParamInterceptor"/>
    </plugins>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test-blog?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai&amp;allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/BlogMapper.xml"/>
    </mappers>
</configuration>
-- ----------------------------
-- Table structure for blog
-- ----------------------------
DROP TABLE IF EXISTS `blog`;
CREATE TABLE `blog`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of blog
-- ----------------------------
INSERT INTO `blog` VALUES (1, 'xxxx');

Steps to reproduce

I reset the parameter values in the ParameterIntercepts Plugin.

statementHandler.getParameterHandler().setParameters((PreparedStatement) invocation.getArgs()[0]);

However the parameter logging included both the old and new parameter values, which is the issue.

Expected result

DEBUG [main] - ==>  Preparing: select * from Blog where id = ?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1

Actual result

DEBUG [main] - ==>  Preparing: select * from Blog where id = ?
DEBUG [main] - ==> Parameters: 1(Integer), 1(Integer), 1(Integer), 1(Integer)
DEBUG [main] - <==      Total: 1
harawata commented 6 months ago

Hello @qiaomengnan16 ,

If you do weird things in a plugin, unexpected things happen. I don't think this is something we need to fix.

qiaomengnan16 commented 6 months ago

Hello @harawata ,

In my business scenario, some data processing (such as encryption, data masking) is uniformly handled within the plugin, and then put it back into the parameters.

However, this led to a logging issue where old and new parameter values appeared together in the logs. If one does not carefully observe the new parameters that follow in the log, it might give the impression that the processing operation did not take effect, which could also potentially cause confusion for others.


Object getParameterObject = statementHandler.getStatementHandler().getParameterHandler().getParameterObject();
String password = ReflectUtils.getFieldValue("password", parameterObject);
password = Util.encryption(password);
ReflectUtils.setFieldValue("password", parameterObject, password);
statementHandler.getParameterHandler().setParameters((PreparedStatement) invocation.getArgs()[0]);
harawata commented 6 months ago

You can do whatever you want in your plugin, but you need to understand it is done at your own risk. We do not modify internal implementation just to make it compatible with your plugin.

I may not fully understand your requirements, but if you want to rewrite parameter properties, StatementHandler#query probably is not the right place to do it. If you post a question to the mailing list or stack overflow with the details about the requirements, someone might propose a better solution.

Closing as won't fix.

qiaomengnan16 commented 6 months ago

Hello @harawata ,

I've identified a more appropriate point for intercepting. The root cause of the issue stemmed from the repeated invocation of the StatementHandler.getParameterHandler().setParameters method.

To address this, I've adjusted the intercept point to modify parameters during the execution of the StatementHandler.parameterize method.

thank you.