반응형

Specification를 활용한 Dynamic Query

Student

@Entity
data class Student(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0L,
    val name: String,
    val desc: String,
    val age: Int,
    val createdAt: LocalDateTime,
)

StudentRepository

@Repository
interface StudentRepository : JpaRepository<Student, Long>, JpaSpecificationExecutor<Student>

예시1

val pageable = PageRequest.of(0, 100, Sort.by(Sort.Direction.DESC, "id"))

val spec = Specification
    .where<Student> { root, query, cb ->
        if (name == null) null else cb.equal(root.get<String>("name"), name)
    }
    .and { root, query, cb ->
        if (age == null) null else cb.greaterThanOrEqualTo(root.get("age"), age)
    }

val result = studentRepository.findAll(spec, pageable)

예시2

val pageable = PageRequest.of(0, 100, Sort.by(Sort.Direction.DESC, "id"))

val spec = Specification
    .where<Student> { root, query, cb ->
        cb.ge(root.get("age"), age)
    }
    .and { root, query, cb ->
        cb.or(
            cb.equal(root.get<String>("name"), name),
            cb.like(cb.lower(root.get("desc")), "%${name.lowercase()}%"),
        )
    }

val result = studentRepository.findAll(spec, pageable)
반응형

'Development > JPA' 카테고리의 다른 글

[JPA] 기본  (0) 2023.11.08

+ Recent posts