Skip to content

Write repository class without interface and also use SimpleJpaRepository with convenience.

Notifications You must be signed in to change notification settings

i978sukhoi/spring-querydsl-helper

Repository files navigation

Spring QueryDSL helper

QRepositoy

Write repository class without interface and also can use SimpleJpaRepository with convenience.

Spring Data JPA already has great support for QueryDSL. but inheriting QuerydslRepositorySupport or QuerydslJpaPredicateExecutor is little messy.

QRepository is abstract class that ...

  • can use findAll, findOne, count.
  • can refer Q class by internal value table.
  • can use findById, save by inherited SimpleJpaRepository
    (also can use Specification style query)
  • can use all QueryDSL functionality by internal value querydsl.
@Repository
class NoticeRepository(entityManager: EntityManager) :
     QRepository<Notice, Int, QNotice>(QNotice.notice, entityManager) {

     fun findTop10ByFilters(type: String, name:String?) = findAll(
         builder(table.type.eq(type))
             .andIf(!name.isNullOrEmpty(), { table.name.like("%$name%") })
     , table.id.desc(), 10L)
}

Extensions

fallowing kotlin extension functions provided.

BooleanBuilder.andIf()

add where clue in conditionally within chain call

val predicate = BooleanBuilder()
    .and(table.type.eq(type))
    .andIf(category.isNotEmpty(), table.category.eq(category))
    .andIf(!name.isNullOrEmpty()) { // to avoid NPE
        table.name.eq(name) // << if name is null, NPE
    }   

NumberPath.nullSafeSum()

because sum(columnName) can be null, should use as coalesce(sum(columnName), 0) in many cases.

JPQLQuery.selectTuple()

shortcut for JPQLQuery.select by constructor projection of TupleN

querydsl.createQuery(table)
    .selectTuple(table.myGroup, table.id.count())
    .groupBy(table.myGroup)
    .fetch()    // = List<Tuple2<String, Long>>
    .forEach {
        println(it.v1, it.v2)
    }
// is equivalent below
querydsl.createQuery(table)
    .select(
        Projections.constructor(
            Tuple2("", 0L).javaClass,
            table.myGroup, table.id.count()
        )
    )
    .groupBy(table.myGroup)
    .fetch()    // = List<Tuple2<String, Long>>
    .forEach {
        println(it.v1, it.v2)
    }

JPQLQuery.forEach (hibernate only)

Hibernate already has stream support. but, QueryDSL does not. This extension function

  • receive lambda
  • convert JPQLQuery to hibernate Query
  • retrieve stream from Query
  • run lambda for each rows

About

Write repository class without interface and also use SimpleJpaRepository with convenience.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages