Programming/Spring

Criteria API

osean 2023. 1. 28. 08:42

  • Criteria API
  • CriteriaBuilder
  • CriteriaQuery

Java Persistence Criteria API ๋Š” JPQL ์˜ ๋ฌธ์ž์—ด ๊ธฐ๋ฐ˜ ์ ‘๊ทผ ๋ฐฉ์‹์„ ์ด์šฉํ•˜๋Š” ๋Œ€์‹  ๊ฐ์ฒด ๊ธฐ๋ฐ˜ ์ฟผ๋ฆฌ ์ •์˜ ๊ฐœ์ฒด์˜ ๊ตฌ์„ฑ์„ ํ†ตํ•ด ๋™์  ์ฟผ๋ฆฌ๋ฅผ ์ •์˜ํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋œ๋‹ค. Critera API ์—๋Š” type-restricted mode, non-typed mode ๋กœ ๋‚˜๋‰˜๋ฉฐ, ๋Ÿฐํƒ€์ž„ ์‹œ ๋™์ ์œผ๋กœ ์กฐํšŒ ๋นŒ๋“œ๋ฅผ ์ง€์›ํ•ด ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ๊ฒ€์ฆํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•œ๋‹ค. ๋˜ํ•œ Criteria API ๋Š” ๋™์  ์ฟผ๋ฆฌ์—๋งŒ ์‚ฌ์šฉ๋˜์–ด ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ ๋˜๋Š” Named Query ์—์„œ๋Š” ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์œผ๋ฉฐ ๋™์  ์ฟผ๋ฆฌ์—์„œ๋งŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์–ด ๊ธฐ์กด์˜ ์ •์  Named Query ์— ๋น„ํ•ด ์„ฑ๋Šฅ์ด ๋›ฐ์–ด๋‚˜์ง€ ์•Š๋‹ค. ๊ทธ๋Ÿฌํ•œ ์ด์œ ๋กœ JPA Provider ๋ฅผ ํ†ตํ•ด ๊ตฌ๋ฌธ ๋ถ„์„ ์บ์‹œ์˜ ์ด์ ์„ ์–ป๋Š” JPQL ๋ณด๋‹ค ์„ฑ๋Šฅ์ด ๋–จ์–ด์ง„๋‹ค.

(JPA 2.1 ๋ถ€ํ„ฐ CriteriaUpdate, CriteraiaDelete ๋ฅผ ์ง€์›ํ•œ๋‹ค.)

CriteraBuilder

CriteraBuilder ๋Š” Critera API ์˜ ๊ธฐ๋ณธ ์ธํ„ฐํŽ˜์ด์Šค๋กœ, EntityManager ๋˜๋Š” EntityManagerFactory ๋ฅผ ํ†ตํ•ด getCriteriaBuilder() API ๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ Builer ๊ตฌํ˜„์ฒด๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค. 
  • createQuery()
  • createQuery(Class)
  • createTupleQuery()
  • createCriteriaDelete(Class)
  • createCriteriaUpdate(Class)

CriteriaQuery

CriteriaQuery ๋Š” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ Select Query ๋ฅผ ์ •์˜ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ JPQL Select Query ์˜ ๋ชจ๋“  ๊ตฌ๋ฌธ์„ ๋ชจ๋ธ๋งํ•œ๋‹ค.
CriteriaQuery ์ž‘์„ฑ ์‹œ, ํ•ด๋‹น ์ฟผ๋ฆฌ์—์„œ ์‚ฌ์šฉ๋œ ์š”์†Œ๋Š” ๋‹ค๋ฅธ CriteriaQuery ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†์œผ๋ฉฐ, EntityManager ์˜ createQuery() ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด JPA ์ฟผ๋ฆฌ๊ฐ€ ์ƒ์„ฑ๋œ๋‹ค.
  • distinct(Boolean)
  • from(Class)
  • from(EntityType)
  • select(Selection)
  • multiselect(Selection...)
  • where(Expression)
  • orderBy(Order...)
  • groupBy(Expression...)
  • having(Expression)
  • subQuery(Class)

Example

@Component
class EBootCriteria(
    @PersistenceContext
    private val entityManager: EntityManager
) {

    fun getEBook(): List<EBook> {
        val criteriaBuilder = entityManager.criteriaBuilder
        val criteriaQuery = criteriaBuilder.createQuery(EBook::class.java)
        val root = criteriaQuery.from(EBook::class.java)
        val isEquals = criteriaBuilder.equal(root.get<String>("name"), "Clean Code")

        criteriaQuery.select(root)
            .distinct(true)
            .where(isEquals)

        val query: TypedQuery<EBook> = entityManager.createQuery(criteriaQuery)

        return query.resultList
    }
}

 

 

 

'Programming > Spring' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Spring Security] @AuthenticationPrincipal Test Trouble Shooting  (0) 2023.04.08
[QueryDSL] NoSuchMethodError Trouble Shooting  (0) 2023.02.22
Spring Bean / IoC Container / DI  (1) 2023.01.21
JPA / Persistence Context / Transactional  (2) 2023.01.14
Spring | Spring Framework ?  (0) 2020.08.02