我已经将 jooq 与 spring 集成在一起,对于所有类型的数据库 (MySQL) 查询,我使用的是 spring 的 JDBC 模板。这里使用 jooq 库来生成传递给 jdbc 模板的 sql 查询。
尽管在我向查询添加限制和/或偏移量之前,其余查询工作正常。
我正在生成如下查询:
create.select(Factory.field("table_name"))
.from("tables t")
.where("t.table_schema LIKE '" + schemaName + "'")
.limit(10)
.offset(2)
.getSQL();
出现如下错误:
org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [select table_name from tables t where (t.table_schema LIKE 'test') limit ? offset ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? offset ?' at line 1
这清楚地表明传递给 limit 和 offset 方法的值不会附加到查询中。
我搜索了文档,但没有找到实现此目的的任何其他方法。
最佳答案
jOOQ 生成带有绑定(bind)值的 SQL。当您使用 jOOQ 仅呈现 SQL,并使用 Spring 执行它时,您基本上可以选择以下任一选项:
明确地使用内联绑定(bind)值:
像这样,您可以明确告诉 jOOQ 不要为您的 LIMIT .. OFFSET
子句呈现任何绑定(bind)变量
create.select(DSL.field("table_name"))
.from("tables t")
.where("t.table_schema LIKE '" + schemaName + "'")
.limit(DSL.inline(10))
.offset(DSL.inline(2))
.getSQL();
让 jOOQ 内联所有绑定(bind)值:
像这样,你可以告诉 jOOQ 不要渲染任何绑定(bind)变量:
Settings settings = new Settings();
settings.setStatementType(StatementType.STATIC_STATEMENT);
DSLContext create = DSL.using(connection, dialect, settings);
// [...]
从 jOOQ 的查询中提取绑定(bind)值:
像这样,您可以让 jOOQ 在适当的地方渲染绑定(bind)变量,并以正确的顺序提取它们:
Query query =
create.select(DSL.field("table_name"))
.from("tables t")
.where("t.table_schema LIKE '" + schemaName + "'")
.limit(DSL.inline(10))
.offset(DSL.inline(2));
String sql = query.getSQL();
List<Object> bindValues = query.getBindValues();
关于 jOOQ 对绑定(bind)值的理解的更多信息:
http://www.jooq.org/doc/latest/manual/sql-building/bind-values/
关于语法完整性和 SQL 注入(inject)的注意事项
请注意您的查询有点容易出错,因为 schemaName
应该被检查并转义以防它源自用户输入。您可以为它创建一个绑定(bind)值:
create.select(DSL.field("table_name"))
.from("tables t")
.where("t.table_schema LIKE ?", schemaName)
关于java - 限制和偏移的jooq问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13697886/