[Kotlin] Spring Boot QueryDsl

by 민갤

Back End /

build.gradle.kts

plugins {
	kotlin("plugin.jpa") version kotlinVersion
	kotlin("kapt") version kotlinVersion
}

val querydslVersion = "5.0.0"

dependencies {
	implementation("com.querydsl:querydsl-jpa:$querydslVersion")
	// plugin kapt 설정하여 build 후 추가
	kapt("com.querydsl:querydsl-apt:$querydslVersion:jpa")
	kapt("org.springframework.boot:spring-boot-configuration-processor")
}

JPAQueryFactory를 Bean으로 등록

@Configuration
class QueryDslConfig(
    @PersistenceContext
    val entityManager: EntityManager
) {
    @Bean
    fun jpaQueryFactory(): JPAQueryFactory {
        return JPAQueryFactory(entityManager)
    }
}

QuerydslRepositorySupport

@Repository
abstract class CustomQuerydslRepositorySupport(domainClass: Class<*>): QuerydslRepositorySupport(domainClass) {

    private var queryFactory: JPAQueryFactory by Delegates.notNull()

    @PersistenceContext
    override fun setEntityManager(entityManager: EntityManager) {
        super.setEntityManager(entityManager)
        this.queryFactory = JPAQueryFactory(entityManager)
    }

    protected fun <T> select(clazz: Class<T>, vararg expr: Expression<*>): JPAQuery<T> {
        return queryFactory.select(Projections.fields(clazz, *expr))
    }

    protected fun <T> selectFrom(from: EntityPath<T>): JPAQuery<T> {
        return queryFactory.selectFrom(from)
    }
}

Repository

interface UserJpaRepository: JpaRepository<User, Long> {
}
class UserRepository (
    private val userJRepo: UserJpaRepository,
    val query: JPAQueryFactory
) : UserJpaRepository by userJRepo, CustomQuerydslRepositorySupport(User::class.java) {

}

Author

민갤

민갤

Back-End Developer

꾸잉꾸잉하고 웁니다.

로그인

디코에 오신 것을 환영해요!
전문가들의 수많은 아티클 창고 🤓