0

Is there way to create sql query on the fly with MyBatis? To concretize: I have a query, where part of it (but not parameter) needs to be created in the runtime:

         with dummy (id) as (
           values (#{rangeEnd}) union all
           select id - 1 from dummy where id - 1 >= #{rangeStart}   
         ).......

The second part can be used as parameter, but, when trying the query as it is I get an exception:

[SQL0584] NULL or parameter marker in VALUES not allowed.

With plain JDBC I use MessageFormat:

PreparedStatement ps = connection.prepareStatement(
            MessageFormat.format(MY_QUERY, currentRange.getRangeEnd()))

, but I haven't found a way how to do it with MyBatis.

agad
  • 2,152
  • 1
  • 19
  • 31

2 Answers2

0

It's really easy (answer from Dynamic Select SQL statements with MyBatis):

with dummy (id) as (
           values (${rangeEnd}) union all
           select id - 1 from dummy where id - 1 >= #{rangeStart}   
         ).......
Community
  • 1
  • 1
agad
  • 2,152
  • 1
  • 19
  • 31
0

Use @SelectProvider annotation:

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);
}
Italo Borssatto
  • 13,777
  • 7
  • 62
  • 83