动态创建JOOQ查询

时间:2012-12-27 07:31:53

标签: java sql jooq

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

提前致谢。

1 个答案:

答案 0 :(得分:28)

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。您可以随时通过DSL查询对象上的getQuery()方法访问“model”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