我的数据库中有两个表:
CREATE TABLE `AUTHOR` (
`ID` varchar(255) NOT NULL,
`NAME` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
)
CREATE TABLE `BOOK` (
`ID` varchar(255) NOT NULL,
`TITLE` varchar(255) NOT NULL,
`AUTHOR_ID` varchar(255) NOT NULL,
PRIMARY KEY (`ID`),
FOREIGN KEY (`AUTHOR_ID`) REFERENCES `AUTHOR` (`ID`)
)
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,作者和书籍之间存在一种关系:作者可以拥有很多本书。在我的应用程序中,我想获取所有作者,每个作者都有他们的书籍集。现在我用代码实现了这个:
public List<Author> findAll() {
List<Author> authors = dsl.selectFrom(AUTHOR)
.fetchInto(Author.class);
return authors.stream()
.map(author -> new Author(author.getId(), author.getName(), getBooksForAuthor(author.getId())))
.collect(Collectors.toList());
}
private List<Book> getBooksForAuthor(String authorId) {
return dsl.select(BOOK.ID, BOOK.TITLE)
.from(BOOK)
.where(BOOK.AUTHOR_ID.eq(authorId))
.fetchInto(Book.class);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,它需要对数据库进行多次查询。通过一个选择来获取作者,并附加一个查询来获取每位作者的书籍。我尝试连接表,但我不知道如何使用 jooq 正确解析结果。有任何想法吗?