[Kotlin] Spring Boot QueryDsl

Spring Boot

(Update : 2022-06-16)

Language :

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) {

}

민갤

Back-End Developer

백엔드 개발자입니다.