“super-dynamic” query with MyBatis
Question
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.
Solution
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} ).......
OTHER TIPS
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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow