gpt4 book ai didi

java - 如何将动态查询从 QueryDSL 转换为 JOOQ?

转载 作者:太空宇宙 更新时间:2023-11-04 09:21:20 27 4
gpt4 key购买 nike

我使用 QueryDSL 只是在 Spring Boot 2+ 中通过 Spring Data 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;
}

我想以类似透明的方式使用JOOQ,但我不知道如何优雅地做到这一点。我也喜欢 JOOQ 中没有类似 QBooks 的生成结构,尽管我认为 JOOQ 也会生成一些表。总之我很困惑,在网上找不到答案,所以我想问一下可以吗以及如何做。

谢谢

最佳答案

jOOQ 没有特定的“构建器”来构建您的谓词。所有“构建”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;
}

这是假设:

1) 您已注入(inject)正确配置的 DSLContext2) 您正在使用 jOOQ 的代码生成器

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

关于java - 如何将动态查询从 QueryDSL 转换为 JOOQ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58285429/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com