Example usage for org.apache.ibatis.mapping BoundSql getSql

List of usage examples for org.apache.ibatis.mapping BoundSql getSql

Introduction

In this page you can find the example usage for org.apache.ibatis.mapping BoundSql getSql.

Prototype

public String getSql() 

Source Link

Usage

From source file:org.apache.playframework.mybatisplus.plugins.PaginationInterceptor.java

License:Apache License

public Object intercept(Invocation invocation) throws Throwable {

    Object target = invocation.getTarget();
    if (target instanceof StatementHandler) {
        StatementHandler statementHandler = (StatementHandler) target;
        MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
        RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");
        Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration");
        BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
        String originalSql = (String) boundSql.getSql();
        /* ?? *//*from  w w  w  .j  ava 2 s  .c  o  m*/
        if (rowBounds != null && rowBounds != RowBounds.DEFAULT) {

            /* ? */
            IDialect dialect = getiDialect();

            /*
             * <p> ? </p> <p> ???????
             * </p>
             */
            metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
            metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);

            /**
             * <p>
             * 
             * </p>
             * <p>
             *  count
             * </p>
             */
            if (rowBounds instanceof Pagination) {
                Pagination page = (Pagination) rowBounds;
                boolean orderBy = true;
                if (page.isSearchCount()) {
                    /*
                     * COUNT  ORDER BY  SQL
                     */
                    CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql, optimizeType,
                            dialectType, page.isOptimizeCount());
                    orderBy = countOptimize.isOrderBy();
                }
                /*  SQL */
                String buildSql = SqlUtils.concatOrderBy(originalSql, page, orderBy);
                originalSql = dialect.buildPaginationSql(buildSql, page.getOffsetCurrent(), page.getSize());
            }
        }
        /**
         *  SQL 
         */
        metaStatementHandler.setValue("delegate.boundSql.sql", buildSql(originalSql, configuration));
    } else {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameterObject = null;
        RowBounds rowBounds = null;
        if (invocation.getArgs().length > 1) {
            parameterObject = invocation.getArgs()[1];
            rowBounds = (RowBounds) invocation.getArgs()[2];
        }
        /* ??? */
        if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        }

        BoundSql boundSql = mappedStatement.getBoundSql(parameterObject);
        /*
         * <p> ? </p> <p> ???????
         * </p>
         */
        String originalSql = (String) boundSql.getSql();

        /**
         * <p>
         * 
         * </p>
         * <p>
         *  count
         * </p>
         */
        if (rowBounds instanceof Pagination) {
            Connection connection = null;
            try {
                connection = mappedStatement.getConfiguration().getEnvironment().getDataSource()
                        .getConnection();
                Pagination page = (Pagination) rowBounds;
                if (page.isSearchCount()) {
                    /*
                     * COUNT  ORDER BY  SQL
                     */
                    CountOptimize countOptimize = SqlUtils.getCountOptimize(originalSql, optimizeType,
                            dialectType, page.isOptimizeCount());
                    page = this.count(countOptimize.getCountSQL(), connection, mappedStatement, boundSql, page);
                    /**  0  */
                    if (page.getTotal() <= 0) {
                        return invocation.proceed();
                    }
                }
            } finally {
                IOUtils.closeQuietly(connection);
            }
        }
    }

    return invocation.proceed();

}

From source file:org.fire.platform.common.page.sqlsource.PageProviderSqlSource.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override/*ww w. j a va2s . c om*/
public BoundSql getBoundSql(Object parameterObject) {
    BoundSql boundSql = null;
    if (parameterObject instanceof Map && ((Map) parameterObject).containsKey(PROVIDER_OBJECT)) {
        boundSql = providerSqlSource.getBoundSql(((Map) parameterObject).get(PROVIDER_OBJECT));
    } else {
        boundSql = providerSqlSource.getBoundSql(parameterObject);
    }
    if (count) {
        return new BoundSql(configuration, parser.getCountSql(boundSql.getSql()),
                boundSql.getParameterMappings(), parameterObject);
    } else {
        return new BoundSql(configuration, parser.getPageSql(boundSql.getSql()),
                parser.getPageParameterMapping(configuration, boundSql), parameterObject);
    }
}

From source file:org.hx.rainbow.common.dao.impl.DaoMybatisImpl.java

License:Open Source License

@Override
public String getSql(String ds, String namespace, String statement, Map<String, Object> paramData) {
    try {//from w w w  . ja  v  a  2s  .c o m
        MappedStatement ms = getDao(ds).getConfiguration().getMappedStatement(namespace + "." + statement);
        BoundSql boundSql = ms.getBoundSql(paramData);
        return boundSql.getSql();
    } catch (Exception e) {
        return namespace + "." + statement + "is error!";
    }
}

From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java

License:Apache License

@Test
void testCustomThymeleafConfig() {
    this.context.register(ThymeleafCustomLanguageDriverConfig.class,
            MybatisLanguageDriverAutoConfiguration.class);
    this.context.refresh();
    ThymeleafLanguageDriver driver = this.context.getBean(ThymeleafLanguageDriver.class);
    SqlSource sqlSource = driver.createSqlSource(new Configuration(),
            "SELECT * FROM users WHERE id = /*[# m:p='id']*/ 1 /*[/]*/", Integer.class);
    BoundSql boundSql = sqlSource.getBoundSql(10);
    assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?");
    assertThat(boundSql.getParameterObject()).isEqualTo(10);
    assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id");
    assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class);
    ThymeleafLanguageDriverConfig config = this.context.getBean(ThymeleafLanguageDriverConfig.class);
    assertThat(config.isUse2way()).isEqualTo(true);
    assertThat(config.getDialect().getPrefix()).isEqualTo("m");
    assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).isNull();
    assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('\\');
    assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("ESCAPE '%s'");
    assertThat(config.getTemplateFile().getBaseDir()).isEqualTo("");
    assertThat(config.getTemplateFile().getCacheTtl()).isNull();
    assertThat(config.getTemplateFile().getEncoding()).isEqualTo(StandardCharsets.UTF_8);
    assertThat(config.getTemplateFile().getPatterns()).hasSize(1).contains("*.sql");
    assertThat(config.getCustomizer()).isNull();
}

From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java

License:Apache License

@Test
void testCustomFreeMarkerConfig() {
    this.context.register(FreeMarkerCustomLanguageDriverConfig.class,
            MybatisLanguageDriverAutoConfiguration.class);
    this.context.refresh();
    FreeMarkerLanguageDriver driver = this.context.getBean(FreeMarkerLanguageDriver.class);
    @SuppressWarnings("unused")
    class Param {
        private Integer id;
        private Integer version;
    }//  www . j  ava 2s  .  c om
    Param params = new Param();
    params.id = 10;
    params.version = 20;
    SqlSource sqlSource = driver.createSqlSource(new Configuration(),
            "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class);
    BoundSql boundSql = sqlSource.getBoundSql(params);
    assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?");
    assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id");
    assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class);
    assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version");
    assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class);
    FreeMarkerLanguageDriverConfig config = this.context.getBean(FreeMarkerLanguageDriverConfig.class);
    assertThat(config.getBasePackage()).isEqualTo("");
    assertThat(config.getFreemarkerSettings()).hasSize(1);
    assertThat(config.getFreemarkerSettings().get("interpolation_syntax")).isEqualTo("dollar");
}

From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java

License:Apache License

@Test
void testCustomVelocityConfig() {
    this.context.register(VelocityCustomLanguageDriverConfig.class,
            MybatisLanguageDriverAutoConfiguration.class);
    this.context.refresh();
    VelocityLanguageDriver driver = this.context.getBean(VelocityLanguageDriver.class);
    @SuppressWarnings("unused")
    class Param {
        private Integer id;
        private Integer version;
    }//from   ww w. j a va  2 s  .c  o m
    Param params = new Param();
    params.id = 10;
    params.version = 20;
    SqlSource sqlSource = driver.createSqlSource(new Configuration(), "#now()", Param.class);
    BoundSql boundSql = sqlSource.getBoundSql(params);
    assertThat(boundSql.getSql()).isEqualTo("SELECT CURRENT_TIMESTAMP");
    VelocityLanguageDriverConfig config = this.context.getBean(VelocityLanguageDriverConfig.class);
    @SuppressWarnings("deprecation")
    String[] userDirective = config.getUserdirective();
    assertThat(userDirective).hasSize(0);
    assertThat(config.getAdditionalContextAttributes()).hasSize(0);
    assertThat(config.getVelocitySettings()).hasSize(3);
    assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADERS)).isEqualTo("class");
    assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADER + ".class.class"))
            .isEqualTo("org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    assertThat(config.generateCustomDirectivesString()).isEqualTo(NowDirective.class.getName()
            + ",org.mybatis.scripting.velocity.TrimDirective,org.mybatis.scripting.velocity.WhereDirective,org.mybatis.scripting.velocity.SetDirective,org.mybatis.scripting.velocity.InDirective,org.mybatis.scripting.velocity.RepeatDirective");
}

From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java

License:Apache License

@Test
void testCustomThymeleafConfigUsingConfigurationProperty() {
    TestPropertyValues.of("mybatis.scripting-language-driver.thymeleaf.use2way=false",
            "mybatis.scripting-language-driver.thymeleaf.dialect.like-additional-escape-target-chars=*,?",
            "mybatis.scripting-language-driver.thymeleaf.dialect.like-escape-char=~",
            "mybatis.scripting-language-driver.thymeleaf.dialect.like-escape-clause-format=escape '%s'",
            "mybatis.scripting-language-driver.thymeleaf.dialect.prefix=mybatis",
            "mybatis.scripting-language-driver.thymeleaf.template-file.base-dir=sqls",
            "mybatis.scripting-language-driver.thymeleaf.template-file.cache-enabled=false",
            "mybatis.scripting-language-driver.thymeleaf.template-file.cache-ttl=1234",
            "mybatis.scripting-language-driver.thymeleaf.template-file.encoding=Windows-31J",
            "mybatis.scripting-language-driver.thymeleaf.template-file.patterns=*.sql,*.sqlf",
            "mybatis.scripting-language-driver.thymeleaf.customizer=org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest$MyTemplateEngineCustomizer")
            .applyTo(this.context);
    this.context.register(MyAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class);
    this.context.refresh();
    ThymeleafLanguageDriver driver = this.context.getBean(ThymeleafLanguageDriver.class);
    SqlSource sqlSource = driver.createSqlSource(new Configuration(),
            "SELECT * FROM users WHERE id = [# mybatis:p='id' /]", Integer.class);
    BoundSql boundSql = sqlSource.getBoundSql(10);
    assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?");
    assertThat(boundSql.getParameterObject()).isEqualTo(10);
    assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id");
    assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class);
    ThymeleafLanguageDriverConfig config = this.context.getBean(ThymeleafLanguageDriverConfig.class);
    assertThat(config.isUse2way()).isEqualTo(false);
    assertThat(config.getDialect().getPrefix()).isEqualTo("mybatis");
    assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).hasSize(2).contains('*', '?');
    assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('~');
    assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("escape '%s'");
    assertThat(config.getTemplateFile().getBaseDir()).isEqualTo("sqls");
    assertThat(config.getTemplateFile().getCacheTtl()).isEqualTo(1234);
    assertThat(config.getTemplateFile().getEncoding()).isEqualTo(Charset.forName("Windows-31J"));
    assertThat(config.getTemplateFile().getPatterns()).hasSize(2).contains("*.sql", "*.sqlf");
    assertThat(config.getCustomizer()).isEqualTo(MyTemplateEngineCustomizer.class);
}

From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java

License:Apache License

@Test
void testCustomFreeMarkerConfigUsingConfigurationProperty() {
    TestPropertyValues.of("mybatis.scripting-language-driver.freemarker.base-package=sqls",
            "mybatis.scripting-language-driver.freemarker.freemarker-settings.interpolation_syntax=dollar",
            "mybatis.scripting-language-driver.freemarker.freemarker-settings.whitespace_stripping=yes")
            .applyTo(this.context);
    this.context.register(MyAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class);
    this.context.refresh();
    FreeMarkerLanguageDriver driver = this.context.getBean(FreeMarkerLanguageDriver.class);
    @SuppressWarnings("unused")
    class Param {
        private Integer id;
        private Integer version;
    }//from  ww w  . j  a  v  a2s.  c  om
    Param params = new Param();
    params.id = 10;
    params.version = 20;
    SqlSource sqlSource = driver.createSqlSource(new Configuration(),
            "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class);
    BoundSql boundSql = sqlSource.getBoundSql(params);
    assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?");
    assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id");
    assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class);
    assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version");
    assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class);
    FreeMarkerLanguageDriverConfig config = this.context.getBean(FreeMarkerLanguageDriverConfig.class);
    assertThat(config.getBasePackage()).isEqualTo("sqls");
    assertThat(config.getFreemarkerSettings()).hasSize(2);
    assertThat(config.getFreemarkerSettings().get("interpolation_syntax")).isEqualTo("dollar");
    assertThat(config.getFreemarkerSettings().get("whitespace_stripping")).isEqualTo("yes");
}

From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java

License:Apache License

@Test
void testCustomVelocityConfigUsingConfigurationProperty() {
    TestPropertyValues.of(// w  ww .j av  a 2s .  c  o  m
            "mybatis.scripting-language-driver.velocity.userdirective=" + NowDirective.class.getName(),
            "mybatis.scripting-language-driver.velocity.velocity-settings." + RuntimeConstants.INPUT_ENCODING
                    + "=" + RuntimeConstants.ENCODING_DEFAULT,
            "mybatis.scripting-language-driver.velocity.additional-context-attributes.attribute1=java.lang.String",
            "mybatis.scripting-language-driver.velocity.additional-context-attributes.attribute2=java.util.HashMap")
            .applyTo(this.context);
    this.context.register(MyAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class);
    this.context.refresh();
    VelocityLanguageDriver driver = this.context.getBean(VelocityLanguageDriver.class);
    @SuppressWarnings("unused")
    class Param {
        private Integer id;
        private Integer version;
    }
    Param params = new Param();
    params.id = 10;
    params.version = 20;
    SqlSource sqlSource = driver.createSqlSource(new Configuration(), "#now()", Param.class);
    BoundSql boundSql = sqlSource.getBoundSql(params);
    assertThat(boundSql.getSql()).isEqualTo("SELECT CURRENT_TIMESTAMP");
    VelocityLanguageDriverConfig config = this.context.getBean(VelocityLanguageDriverConfig.class);
    @SuppressWarnings("deprecation")
    String[] userDirective = config.getUserdirective();
    assertThat(userDirective).hasSize(1).contains(NowDirective.class.getName());
    assertThat(config.getAdditionalContextAttributes()).hasSize(2);
    assertThat(config.getAdditionalContextAttributes().get("attribute1")).isEqualTo("java.lang.String");
    assertThat(config.getAdditionalContextAttributes().get("attribute2")).isEqualTo("java.util.HashMap");
    assertThat(config.getVelocitySettings()).hasSize(3);
    assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADERS)).isEqualTo("class");
    assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADER + ".class.class"))
            .isEqualTo("org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    assertThat(config.generateCustomDirectivesString()).isEqualTo(NowDirective.class.getName()
            + ",org.mybatis.scripting.velocity.TrimDirective,org.mybatis.scripting.velocity.WhereDirective,org.mybatis.scripting.velocity.SetDirective,org.mybatis.scripting.velocity.InDirective,org.mybatis.scripting.velocity.RepeatDirective");
    assertThat(config.getVelocitySettings().get(RuntimeConstants.INPUT_ENCODING))
            .isEqualTo(RuntimeConstants.ENCODING_DEFAULT);

}

From source file:org.nebula.service.dao.PaginationInterceptor.java

License:Apache License

public Object intercept(Invocation inv) throws Throwable {

    StatementHandler target = (StatementHandler) inv.getTarget();
    BoundSql boundSql = target.getBoundSql();
    String sql = boundSql.getSql();
    if (StringUtils.isBlank(sql)) {
        return inv.proceed();
    }/*from   w ww. ja v  a2s. c  o m*/
    logger.debug("origin sql>>>>>" + sql.replaceAll("\n", ""));
    // ?select??
    if (sql.matches(SQL_SELECT_REGEX) && !Pattern.matches(SQL_COUNT_REGEX, sql)) {
        Object obj = FieldUtils.readField(target, "delegate", true);
        // ??? RowBounds 
        RowBounds rowBounds = (RowBounds) FieldUtils.readField(obj, "rowBounds", true);
        // ??SQL
        if (rowBounds != null && rowBounds != RowBounds.DEFAULT) {
            FieldUtils.writeField(boundSql, "sql", newSql(sql, rowBounds), true);
            logger.debug("new sql>>>>>" + boundSql.getSql().replaceAll("\n", ""));
            // ???(?)
            FieldUtils.writeField(rowBounds, "offset", RowBounds.NO_ROW_OFFSET, true);
            FieldUtils.writeField(rowBounds, "limit", RowBounds.NO_ROW_LIMIT, true);
        }
    }
    return inv.proceed();
}