Spring Data JPA + QueryDSL实现CRUD和复杂查询案例


Spring Data JPA仅执行CRUD操作,而对于所有复杂的查询,使用QueryDSL。
可以使用此链接在GitHub上找到完整的项目。有一个简单的SpringBoot应用程序,具有配置的MySQL数据源和称为Flyway迁移的初始数据库结构。
引入QueryDSL:

<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-apt</artifactId>
</dependency>

查询Java写法:
public List<Author> findAllWithBooks() {
        return queryFactory
                .select(author).distinct()
                .from(author)
                .innerJoin(author.books, book).fetchJoin()
                .fetch();
 }
输出SQL:

select distinct author0_.id as id1_0_0_, books1_.id as id1_1_1_, author0_.email as email2_0_0_, author0_.full_name as full_nam3_0_0_, books1_.author_id as author_i4_1_1_, books1_.iban as iban2_1_1_, books1_.name as name3_1_1_, books1_.author_id as author_i4_1_0__, books1_.id as id1_1_0__ from author author0_ inner join book books1_ on author0_.id=books1_.author_id

如您所见,仅执行了一个查询。作者的所有书籍都将被加载,并且不会有其他子选择或LazyLoadingExceptions。
distinct() 原始查询中使用运算符从结果中删除作者重复项。