12

我需要根据参数集动态创建一个 JOOQ SELECT 查询。我不知道如何动态附加它。请帮忙

提前致谢。

4

1 回答 1

33

jOOQ 有两种类型的 API 来构造查询。

  • 允许在 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

此处的手册中给出了您想要执行的操作的示例:

https://www.jooq.org/doc/latest/manual/sql-building/sql-statements/dsl-and-non-dsl/

例如,可选地添加一个连接:

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();

或者,可选择添加条件/谓词:

query.addConditions(BOOK.TITLE.like("%Java%"));
query.addConditions(BOOK.LANGUAGE_CD.eq("en"));

更新:鉴于您的评论,这就是您正在寻找的:

// 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));

请注意,您还可以使用以下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));

有关更多信息,请考虑org.jooq.SelectQuery Javadoc

于 2012-12-27T10:26:29.053 回答