Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix parameter logging issue #3110

Closed
wants to merge 1 commit into from

Conversation

qiaomengnan16
Copy link

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
Copy link
Member

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
Copy link
Author

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
Copy link
Member

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.

@harawata harawata closed this Mar 15, 2024
@qiaomengnan16
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants