iBatis配置log4j输出SQL详解

在log4j.properties文件配置如下内容即可输入SQL语句了

  1. # Preparing Statement: SQL
  2. log4j.logger.java.sql.Connection = DEBUG  
  3. # Executing Statement: SQL / Parameters / Types
  4. log4j.logger.java.sql.Statement = DEBUG  
  5. log4j.logger.java.sql.PreparedStatement = DEBUG  
  6. # ResultSet: Header / Result
  7. #log4j.logger.java.sql.ResultSet = DEBUG  

下面是配置详解,够详细吧!

配置这一句就会输出SQL
log4j.logger.java.sql.Connection = DEBUG
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {conn-100006} Connection
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {conn-100006} Preparing Statement: SELECT id, name FROM t_sys_role WHERE role_id = ?
配置这两句就会输出调用SQL的参数值和类型
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {pstm-100007} Executing Statement: SELECT id, name FROM t_sys_role WHERE role_id = ?
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {pstm-100007} Parameters: [500002]
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {pstm-100007} Types: [java.lang.Integer]
配置这一句就会输出调用SQL的执行结果
log4j.logger.java.sql.ResultSet = DEBUG
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {rset-100008} ResultSet
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {rset-100008} Header: [id, name]
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {rset-100008} Result: [810001, 首页]
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {rset-100008} Result: [810002, 注册]
    [DEBUG] com.ibatis.common.logging.jakarta.JakartaCommonsLoggingImpl
    {rset-100008} Result: [810003, 下载]

执行结果一般数据比较多,最好不要输出,所以配这三条就好了
log4j.logger.java.sql.Connection = DEBUG
log4j.logger.java.sql.Statement = DEBUG
log4j.logger.java.sql.PreparedStatement = DEBUG

曾经有一个项目,希望将SQL输出到日志中,特意写了一个方法,每次执行前调用一次,那叫一个复杂啊!

public String getSqlString(String sqlId, Object params) {
    SqlMapClientImpl sqlmap = (SqlMapClientImpl) getSqlMapClient();
    SqlMapSession session = sqlmap.openSession();
    
    SessionScope sessionScope = new SessionScope();
    sessionScope.setSqlMapClient(sqlmap);
    sessionScope.setSqlMapExecutor(sqlmap);
    sessionScope.setSqlMapTxMgr(session);
    
    StatementScope statementScope = new StatementScope(sessionScope);
    sessionScope.incrementRequestStackDepth();
    SqlMapExecutorDelegate delegate = sqlmap.getDelegate();
    MappedStatement ms = delegate.getMappedStatement(sqlId);
    ms.initRequest(statementScope);

    MappedStatement stmt = sqlmap.getMappedStatement(sqlId);
    Sql sql = stmt.getSql();
    String string = sql.getSql(statementScope, params);
    session.close();
    return string;
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。