QueryDslhttp://querydsl.com/

1、添加插件和依赖

val queryDslVersion = "5.0.0"

plugins {
    id("org.jetbrains.kotlin.kapt") version "1.6.10"
}

dependencies {
    implementation("com.querydsl:querydsl-core:$queryDslVersion")
    implementation("com.querydsl:querydsl-jpa:$queryDslVersion")
    kapt("com.querydsl:querydsl-apt:$queryDslVersion:jpa")
}

querydsl会扫描带有@Entity注解的类,在build/generated/source/kapt下生成Q+entity名字的类

2、运算符重载

BooleanBuilder添加一个+号重载

operator fun BooleanBuilder.plus(right: Predicate) {
    this.and(right)
}

3、entity

@Entity
@Table(name = "lolicon")
class LoLiConEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Int? = null
    @Column(unique = true)
    var pid: Long = 0
    var p: Int = 0
    var uid: Long = 0
    var title: String = ""
    var author: String = ""
    var url: String = ""
    var tags: String = ""
    @Column(name = "quick_url")
    var quickUrl: String? = ""
}

querydsl就会生成一个QLoLiConEntity的类在指定包下

4、repository

继承于QuerydslPredicateExecutor

interface LoLiConRepository: JpaRepository<LoLiConEntity, Int>, QuerydslPredicateExecutor<LoLiConEntity>

5、编写动态查询

fun findAll(loLiConEntity: LoLiConEntity, pageable: Pageable): Page<LoLiConEntity> {
        val bb = BooleanBuilder()
        val qLoLiConEntity = QLoLiConEntity.loLiConEntity
        if (loLiConEntity.id != null) bb + qLoLiConEntity.id.eq(loLiConEntity.id)
        if (loLiConEntity.author.isNotEmpty()) bb + qLoLiConEntity.author.like("%${loLiConEntity.author}%")
        if (loLiConEntity.pid != 0L) bb + qLoLiConEntity.pid.eq(loLiConEntity.pid)
        if (loLiConEntity.uid != 0L) bb + qLoLiConEntity.uid.eq(loLiConEntity.uid)
        if (loLiConEntity.title.isNotEmpty()) bb + qLoLiConEntity.title.like("%${loLiConEntity.title}%")
        if (loLiConEntity.tags.isNotEmpty()) bb + qLoLiConEntity.tags.like("%${loLiConEntity.tags}%")
        return loLiConRepository.findAll(bb, pageable)
}

6、使用JpaQueryFactory进行查询

JpaQueryFactory添加到Spring容器

@Bean
open fun jpaQueryFactory(entityManager: EntityManager): JPAQueryFactory {
    return JPAQueryFactory(entityManager)
}

使用JpaQueryFactory查询

val bb = BooleanBuilder()
val qLoLiConEntity = QLoLiConEntity.loLiConEntity
val jpaQueryFactory = applicationContext.getBean(JPAQueryFactory::class.java)
val list = jpaQueryFactory.selectFrom(qLoLiConEntity).where(bb).orderBy(qLoLiConEntity.id.desc())
            .offset(0).limit(20).fetch()
最后修改:2021 年 12 月 16 日
如果觉得我的文章对你有用,请随意赞赏