简体   繁体   English

如何将 QueryDSL 中的动态查询转换为 JOOQ?

[英]How to translate dynamic query from QueryDSL into JOOQ?

I use QueryDSL just for dynamic queries in Spring Boot 2+ with Spring Data JPA applications in the following manner:我将 QueryDSL用于 Spring Boot 2+ 中的动态查询,其中 Spring 数据 JPA 应用程序采用以下方式:

@Override
public Iterable<Books> search(String bookTitle, String bookAuthor, String bookGenre) {
  BooleanBuilder where = dynamicWhere(bookTitle, bookAuthor, bookGenre);
  return booksRepository.findAll(where, orderByTitle());
}

public BooleanBuilder dynamicWhere(String bookTitle, String bookAuthor, String bookGenre) {
  QBooks qBooks = QBooks.books;
  BooleanBuilder where = new BooleanBuilder();
  if (bookTitle != null) {
    where.and(qBooks.title.equalsIgnoreCase(bookTitle));
  }
  if (bookAuthor!= null) {
    where.and(qBooks.author.eq(bookAuthor));
  }
  if (bookGenre!= null) {
    where.and(qBooks.genre.eq(bookGenre));
  }
  return where;
}

I want to use JOOQ in a similar transparent way, but I do not know how to do it elegantly.我想以类似透明的方式使用 JOOQ,但我不知道如何优雅地做到这一点。 I also like that in JOOQ there isn't QBooks-like generated constructs, although I think JOOQ also generates some tables.我也喜欢 JOOQ 中没有类似 QBooks 的生成结构,尽管我认为 JOOQ 也会生成一些表。 Anyhow, I am confused and I couldn't find an answer online, so I am asking can it be done and how.无论如何,我很困惑,我无法在网上找到答案,所以我问它是否可以完成以及如何完成。

Thanks谢谢

jOOQ doesn't have a specific "builder" to construct your predicates. jOOQ 没有特定的“构建器”来构建您的谓词。 All the "building" API is located directly on the predicate type, ie the Condition所有的“建筑”API都直接位于谓词类型上,即Condition

@Override
public Iterable<Books> search(String bookTitle, String bookAuthor, String bookGenre) {
  Condition where = dynamicWhere(bookTitle, bookAuthor, bookGenre);
  return dslContext.selectFrom(BOOKS)
                   .where(where)
                   .orderBy(BOOKS.TITLE)
                   .fetchInto(Books.class);
}

public Condition dynamicWhere(String bookTitle, String bookAuthor, String bookGenre) {
  Condition where = DSL.noCondition();
  if (bookTitle != null) {
    where = where.and(BOOKS.TITLE.equalsIgnoreCase(bookTitle));
  }
  if (bookAuthor!= null) {
    where = where.and(BOOKS.AUTHOR.eq(bookAuthor));
  }
  if (bookGenre!= null) {
    where = where.and(BOOKS.GENRE.eq(bookGenre));
  }
  return where;
}

This is assuming:这是假设:

1) That you have injected a properly configured DSLContext 2) That you're using jOOQ's code generator 1)您已经注入了正确配置的DSLContext 2)您正在使用 jOOQ 的代码生成器

For more information, see also https://www.jooq.org/doc/latest/manual/sql-building/dynamic-sql/有关更多信息,另请参阅https://www.jooq.org/doc/latest/manual/sql-building/dynamic-sql/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM