iBatis 获取执行的sql

发布于 2024-08-29 04:15:30 字数 562 浏览 8 评论 0原文

有什么方法可以获取 iBatis 执行的查询吗?我想将查询重用为 UNION 查询。

例如:

<sqlMap namespace="userSQLMap">
   <select id="getUser" resultClass="UserPackage.User">
        SELECT username,
               password 
        FROM table 
        WHERE id=#value#
   </select>
</sqlMap>

当我通过执行查询时,

int id = 1
List<User> userList = queryDAO.executeForObjectList("userSQLMap.getUser",id)

我想获取SELECT username,password FROM table WHERE id=1

有什么方法可以获取查询吗?

谢谢。

Is there any way where I can get the executed query of iBatis? I want to reuse the query for an UNION query.

For example:

<sqlMap namespace="userSQLMap">
   <select id="getUser" resultClass="UserPackage.User">
        SELECT username,
               password 
        FROM table 
        WHERE id=#value#
   </select>
</sqlMap>

And when I execute the query through

int id = 1
List<User> userList = queryDAO.executeForObjectList("userSQLMap.getUser",id)

I want to get SELECT username, password FROM table WHERE id=1

Is there any way I could get the query?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

终弃我 2024-09-05 04:15:30

将其添加到您的 log4j.xml 文件中,您可以在控制台上看到输出。

<logger name="java.sql" additivity="false">
    <level value="debug" />
    <appender-ref ref="console" />
</logger>

您将看到正在传递的参数、正在执行的查询以及查询的输出。

Add this to your log4j.xml file and you can see the output on console.

<logger name="java.sql" additivity="false">
    <level value="debug" />
    <appender-ref ref="console" />
</logger>

You will see the parameters being passed, the query being executed and the output of query.

哎呦我呸! 2024-09-05 04:15:30

可以显示这些信息。iBatis 使用一些日志框架,包括 Log4J
要使用 Log4J 在类路径中创建文件 log4j.properties。您必须将以下几行放入该文件中,例如:

log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
    
log4j.logger.com.ibatis=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG

有关其他日志记录框架和详细信息,请参阅 < a href="http://ibatisnet.sourceforge.net/DevGuide.html#d0e2600" rel="nofollow noreferrer">此链接

It's posible to show this information.iBatis uses some the Logging framework including Log4J.
To use Log4J create file log4j.properties in the class path.You've to put the next lines in the file for example:

log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
    
log4j.logger.com.ibatis=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG

For other logging framework and detail info see this link

风月客 2024-09-05 04:15:30

SqlSessionFactory 获取 Configuration 对象,然后:

MappedStatement ms = configuration.getMappedStatement("MyMappedStatementId");
BoundSql boundSql = ms.getBoundSql(parameters); // pass in parameters for the SQL statement
System.out.println("SQL" + boundSql.getSql());

Get the Configuration object from your SqlSessionFactory, then:

MappedStatement ms = configuration.getMappedStatement("MyMappedStatementId");
BoundSql boundSql = ms.getBoundSql(parameters); // pass in parameters for the SQL statement
System.out.println("SQL" + boundSql.getSql());
可是我不能没有你 2024-09-05 04:15:30
    import java.util.Properties;
    import org.apache.ibatis.executor.Executor;
    import org.apache.ibatis.mapping.BoundSql;
    import org.apache.ibatis.mapping.MappedStatement;
    import org.apache.ibatis.mapping.MappedStatement.Builder;
    import org.apache.ibatis.mapping.SqlSource;
    import org.apache.ibatis.plugin.Interceptor;
    import org.apache.ibatis.plugin.Intercepts;
    import org.apache.ibatis.plugin.Invocation;
    import org.apache.ibatis.plugin.Plugin;
    import org.apache.ibatis.plugin.Signature;
    import org.apache.ibatis.session.ResultHandler;
    import org.apache.ibatis.session.RowBounds;

    import com.gm.common.orm.mybatis.dialect.Dialect;
    import com.gm.common.utils.PropertiesHelper;

    /**
     * 为Mybatis提供基于方言(Dialect)的分页查询的插件
     * 
     * 将拦截Executor.query()方法实现分页方言的插入.
     * 
     * 配置文件内容:
     * 
     * <pre>
     *  <plugins>
     *  <plugin interceptor="com.gm.common.orm.mybatis.plugin.OffsetLimitInterceptor">
     *      <property name="dialectClass" value="com.gm.common.orm.mybatis.dialect.MySQLDialect"/>
     *  </plugin>
     * </plugins>
     * </pre>
     */

    @Intercepts({@Signature(type=Executor.class,method="query",args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})})
    public class OffsetLimitInterceptor implements  Interceptor {
        static int MAPPED_STATEMENT_INDEX = 0;
        static int PARAMETER_INDEX = 1;
        static int ROWBOUNDS_INDEX = 2;
        static int RESULT_HANDLER_INDEX = 3;

        Dialect dialect;

        public Object intercept(Invocation invocation) throws Throwable {
            processIntercept(invocation.getArgs());
            return invocation.proceed();
        }

        void processIntercept(final Object[] queryArgs) {
            // queryArgs = query(MappedStatement ms, Object parameter, RowBounds
            // rowBounds, ResultHandler resultHandler)
            MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
            Object parameter = queryArgs[PARAMETER_INDEX];
            final RowBounds rowBounds = (RowBounds) queryArgs[ROWBOUNDS_INDEX];
            int offset = rowBounds.getOffset();
            int limit = rowBounds.getLimit();

            if (dialect.supportsLimit()
                    && (offset != RowBounds.NO_ROW_OFFSET || limit != RowBounds.NO_ROW_LIMIT)) {
                BoundSql boundSql = ms.getBoundSql(parameter);
                String sql = boundSql.getSql().trim();
                if (dialect.supportsLimitOffset()) {
                    sql = dialect.getLimitString(sql, offset, limit);
                    offset = RowBounds.NO_ROW_OFFSET;
                } else {
                    sql = dialect.getLimitString(sql, 0, limit);
                }
                limit = RowBounds.NO_ROW_LIMIT;

                queryArgs[ROWBOUNDS_INDEX] = new RowBounds(offset, limit);
                BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),
                        sql, boundSql.getParameterMappings(), boundSql
                                .getParameterObject());
                MappedStatement newMs = copyFromMappedStatement(ms,
                        new BoundSqlSqlSource(newBoundSql));
                queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
            }
        }

        // see: MapperBuilderAssistant
        private MappedStatement copyFromMappedStatement(MappedStatement ms,
                SqlSource newSqlSource) {
            Builder builder = new MappedStatement.Builder(ms
                    .getConfiguration(), ms.getId(), newSqlSource, ms
                    .getSqlCommandType());

            builder.resource(ms.getResource());
            builder.fetchSize(ms.getFetchSize());
            builder.statementType(ms.getStatementType());
            builder.keyGenerator(ms.getKeyGenerator());
            builder.keyProperty(ms.getKeyProperty());

            // setStatementTimeout()
            builder.timeout(ms.getTimeout());

            // setStatementResultMap()
            builder.parameterMap(ms.getParameterMap());

            // setStatementResultMap()
            builder.resultMaps(ms.getResultMaps());
            builder.resultSetType(ms.getResultSetType());

            // setStatementCache()
            builder.cache(ms.getCache());
            builder.flushCacheRequired(ms.isFlushCacheRequired());
            builder.useCache(ms.isUseCache());

            return builder.build();
        }

        public Object plugin(Object target) {
            return Plugin.wrap(target, this );
        }

        public void setProperties(Properties properties) {
            String dialectClass = new PropertiesHelper(properties)
                    .getRequiredString("dialectClass");
            try {
                dialect = (Dialect) Class.forName(dialectClass)
                        .newInstance();
            } catch (Exception e) {
                throw new RuntimeException(
                        "cannot create dialect instance by dialectClass:"
                                + dialectClass, e);
            }
            System.out.println(OffsetLimitInterceptor.class.getSimpleName()
                    + ".dialect=" + dialectClass);
        }

        public static class BoundSqlSqlSource implements  SqlSource {
            BoundSql boundSql;

            public BoundSqlSqlSource(BoundSql boundSql) {
                this .boundSql = boundSql;
            }

            public BoundSql getBoundSql(Object parameterObject) {
                return boundSql;
            }
        }

    }

我的参考:https://www.java2s.com/Open-Source/Java-Document-2/UnTagged/gmc/com/gm/common/orm/mybatis/plugin/OffsetLimitInterceptor.java.htm

    import java.util.Properties;
    import org.apache.ibatis.executor.Executor;
    import org.apache.ibatis.mapping.BoundSql;
    import org.apache.ibatis.mapping.MappedStatement;
    import org.apache.ibatis.mapping.MappedStatement.Builder;
    import org.apache.ibatis.mapping.SqlSource;
    import org.apache.ibatis.plugin.Interceptor;
    import org.apache.ibatis.plugin.Intercepts;
    import org.apache.ibatis.plugin.Invocation;
    import org.apache.ibatis.plugin.Plugin;
    import org.apache.ibatis.plugin.Signature;
    import org.apache.ibatis.session.ResultHandler;
    import org.apache.ibatis.session.RowBounds;

    import com.gm.common.orm.mybatis.dialect.Dialect;
    import com.gm.common.utils.PropertiesHelper;

    /**
     * 为Mybatis提供基于方言(Dialect)的分页查询的插件
     * 
     * 将拦截Executor.query()方法实现分页方言的插入.
     * 
     * 配置文件内容:
     * 
     * <pre>
     *  <plugins>
     *  <plugin interceptor="com.gm.common.orm.mybatis.plugin.OffsetLimitInterceptor">
     *      <property name="dialectClass" value="com.gm.common.orm.mybatis.dialect.MySQLDialect"/>
     *  </plugin>
     * </plugins>
     * </pre>
     */

    @Intercepts({@Signature(type=Executor.class,method="query",args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})})
    public class OffsetLimitInterceptor implements  Interceptor {
        static int MAPPED_STATEMENT_INDEX = 0;
        static int PARAMETER_INDEX = 1;
        static int ROWBOUNDS_INDEX = 2;
        static int RESULT_HANDLER_INDEX = 3;

        Dialect dialect;

        public Object intercept(Invocation invocation) throws Throwable {
            processIntercept(invocation.getArgs());
            return invocation.proceed();
        }

        void processIntercept(final Object[] queryArgs) {
            // queryArgs = query(MappedStatement ms, Object parameter, RowBounds
            // rowBounds, ResultHandler resultHandler)
            MappedStatement ms = (MappedStatement) queryArgs[MAPPED_STATEMENT_INDEX];
            Object parameter = queryArgs[PARAMETER_INDEX];
            final RowBounds rowBounds = (RowBounds) queryArgs[ROWBOUNDS_INDEX];
            int offset = rowBounds.getOffset();
            int limit = rowBounds.getLimit();

            if (dialect.supportsLimit()
                    && (offset != RowBounds.NO_ROW_OFFSET || limit != RowBounds.NO_ROW_LIMIT)) {
                BoundSql boundSql = ms.getBoundSql(parameter);
                String sql = boundSql.getSql().trim();
                if (dialect.supportsLimitOffset()) {
                    sql = dialect.getLimitString(sql, offset, limit);
                    offset = RowBounds.NO_ROW_OFFSET;
                } else {
                    sql = dialect.getLimitString(sql, 0, limit);
                }
                limit = RowBounds.NO_ROW_LIMIT;

                queryArgs[ROWBOUNDS_INDEX] = new RowBounds(offset, limit);
                BoundSql newBoundSql = new BoundSql(ms.getConfiguration(),
                        sql, boundSql.getParameterMappings(), boundSql
                                .getParameterObject());
                MappedStatement newMs = copyFromMappedStatement(ms,
                        new BoundSqlSqlSource(newBoundSql));
                queryArgs[MAPPED_STATEMENT_INDEX] = newMs;
            }
        }

        // see: MapperBuilderAssistant
        private MappedStatement copyFromMappedStatement(MappedStatement ms,
                SqlSource newSqlSource) {
            Builder builder = new MappedStatement.Builder(ms
                    .getConfiguration(), ms.getId(), newSqlSource, ms
                    .getSqlCommandType());

            builder.resource(ms.getResource());
            builder.fetchSize(ms.getFetchSize());
            builder.statementType(ms.getStatementType());
            builder.keyGenerator(ms.getKeyGenerator());
            builder.keyProperty(ms.getKeyProperty());

            // setStatementTimeout()
            builder.timeout(ms.getTimeout());

            // setStatementResultMap()
            builder.parameterMap(ms.getParameterMap());

            // setStatementResultMap()
            builder.resultMaps(ms.getResultMaps());
            builder.resultSetType(ms.getResultSetType());

            // setStatementCache()
            builder.cache(ms.getCache());
            builder.flushCacheRequired(ms.isFlushCacheRequired());
            builder.useCache(ms.isUseCache());

            return builder.build();
        }

        public Object plugin(Object target) {
            return Plugin.wrap(target, this );
        }

        public void setProperties(Properties properties) {
            String dialectClass = new PropertiesHelper(properties)
                    .getRequiredString("dialectClass");
            try {
                dialect = (Dialect) Class.forName(dialectClass)
                        .newInstance();
            } catch (Exception e) {
                throw new RuntimeException(
                        "cannot create dialect instance by dialectClass:"
                                + dialectClass, e);
            }
            System.out.println(OffsetLimitInterceptor.class.getSimpleName()
                    + ".dialect=" + dialectClass);
        }

        public static class BoundSqlSqlSource implements  SqlSource {
            BoundSql boundSql;

            public BoundSqlSqlSource(BoundSql boundSql) {
                this .boundSql = boundSql;
            }

            public BoundSql getBoundSql(Object parameterObject) {
                return boundSql;
            }
        }

    }

My reference : https://www.java2s.com/Open-Source/Java-Document-2/UnTagged/gmc/com/gm/common/orm/mybatis/plugin/OffsetLimitInterceptor.java.htm

乖不如嘢 2024-09-05 04:15:30

大多数 SQL 引擎允许您“记录”执行的所有查询(通常还包括有关查询所用时间、返回结果数量等信息)。您是否有权访问引擎的日志,并且可以配置它以便它记录您需要的所有内容吗?

Most SQL engines allow you to "log" all the queries executed (typically together with information about the time the query took, the number of results it returned, and the like). Do you have access to your engine's logs, and can you configure it so it will log all you need?

毁梦 2024-09-05 04:15:30

您可以使用 p6spyjdbcdslog 为此。

You can use p6spy or jdbcdslog for that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文