java 动态创建 JOOQ 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14051080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating JOOQ query dynamically
提问by user1900723
I need to create a JOOQ SELECT query dynamically based on the set of parameters. I dont know how to append it dynamically. Please help
我需要根据参数集动态创建 JOOQ SELECT 查询。我不知道如何动态附加它。请帮忙
Thanks in advance.
提前致谢。
回答by Lukas Eder
jOOQ has two types of APIs to construct queries.
jOOQ 有两种类型的 API 来构建查询。
The DSL API that allows for creating inline SQL statements in your Java code, e.g.
create.select(T.A, T.B).from(T).where(T.X.eq(3).and(T.Y.eq(5)));
The "model" API that allows for incremental SQL building. At any time, you can access the "model" API through the
getQuery()
method on a DSL query object
允许在 Java 代码中创建内联 SQL 语句的 DSL API,例如
create.select(T.A, T.B).from(T).where(T.X.eq(3).and(T.Y.eq(5)));
允许增量 SQL 构建的“模型”API。任何时候,您都可以通过
getQuery()
DSL 查询对象上的方法访问“模型”API
An example of what you want to do is given in the manual here:
此处的手册中给出了您想要执行的操作的示例:
https://www.jooq.org/doc/latest/manual/sql-building/sql-statements/dsl-and-non-dsl/
https://www.jooq.org/doc/latest/manual/sql-building/sql-statements/dsl-and-non-dsl/
For instance, optionally adding a join:
例如,可选地添加一个连接:
DSLContext create = DSL.using(configuration);
SelectQuery query = create.selectQuery();
query.addFrom(AUTHOR);
// Join books only under certain circumstances
if (join)
query.addJoin(BOOK, BOOK.AUTHOR_ID.equal(AUTHOR.ID));
Result<?> result = query.fetch();
Or, optinally adding conditions / predicates:
或者,可以选择添加条件/谓词:
query.addConditions(BOOK.TITLE.like("%Java%"));
query.addConditions(BOOK.LANGUAGE_CD.eq("en"));
UPDATE:Given your comments, that's what you're looking for:
更新:根据您的评论,这就是您要查找的内容:
// Retrieve search strings from your user input (just an example)
String titleSearchString = userInput.get("TITLE");
String languageSearchString = userInput.get("LANGUAGE");
boolean lookingForTitles = titleSearchString != null;
boolean lookingForLanguages = languageSearchString != null;
// Add only those conditions that the user actually provided:
if (lookingForTitles)
query.addConditions(BOOK.TITLE.like("%" + titleSearchString + "%"));
else if (lookingForLanguages)
query.addConditions(BOOK.LANGUAGE_CD.eq(languageSearchString));
Note, you can also use the Field.compare(Comparator, Object)
methods:
请注意,您还可以使用以下Field.compare(Comparator, Object)
方法:
// Initialise your dynamic arguments
Field<String> field = BOOK.TITLE;
Comparator comparator = Comparator.LIKE;
String value = "%" + titleSearchString + "%";
// Pass them to the field.compare() method
query.addConditions(field.compare(comparator, value));
For more info, consider the org.jooq.SelectQueryJavadoc
有关更多信息,请考虑org.jooq.SelectQueryJavadoc