Java 使用MyBatis的“超动态”查询

Java 使用MyBatis的“超动态”查询,java,sql,mybatis,db2-400,Java,Sql,Mybatis,Db2 400,有没有办法使用MyBatis动态创建sql查询?具体化:我有一个查询,其中需要在运行时创建部分查询,但不需要创建参数: with dummy (id) as ( values (#{rangeEnd}) union all select id - 1 from dummy where id - 1 >= #{rangeStart} )....... 第二部分可以用作参数,但是,当按原样尝试查询时,我得到

有没有办法使用MyBatis动态创建sql查询?具体化:我有一个查询,其中需要在运行时创建部分查询,但不需要创建参数:

         with dummy (id) as (
           values (#{rangeEnd}) union all
           select id - 1 from dummy where id - 1 >= #{rangeStart}   
         ).......
第二部分可以用作参数,但是,当按原样尝试查询时,我得到一个异常:

[SQL0584] NULL or parameter marker in VALUES not allowed.
对于普通JDBC,我使用MessageFormat:


,但我还没有找到一种方法来使用MyBatis。

答案非常简单:

使用@SelectProvider注释:

public interface SqlMapper {
    static class PureSqlProvider {
        public String sql(String sql) {
           // Create your query here
           return sql; 
        }
    }

    @SelectProvider(type = PureSqlProvider.class, method = "sql")
    public List<Dummy> select(String sql);
}
with dummy (id) as ( values (${rangeEnd}) union all select id - 1 from dummy where id - 1 >= #{rangeStart} ).......
public interface SqlMapper {
    static class PureSqlProvider {
        public String sql(String sql) {
           // Create your query here
           return sql; 
        }
    }

    @SelectProvider(type = PureSqlProvider.class, method = "sql")
    public List<Dummy> select(String sql);
}