在log4j.properties文件配置如下内容即可输入SQL语句了
- # Preparing Statement: SQL
- log4j.logger.java.sql.Connection = DEBUG
- # Executing Statement: SQL / Parameters / Types
- log4j.logger.java.sql.Statement = DEBUG
- log4j.logger.java.sql.PreparedStatement = DEBUG
- # ResultSet: Header / Result
- #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; }