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)
}
fallowing kotlin extension functions provided.
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
}
because sum(columnName)
can be null, should use as coalesce(sum(columnName), 0)
in many cases.
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)
}
Hibernate already has stream support. but, QueryDSL does not. This extension function