line / kotlin-jdsl

Kotlin library that makes it easy to build and execute queries without generated metamodel
https://kotlin-jdsl.gitbook.io/docs/
Apache License 2.0
679 stars 86 forks source link

How can I sort by a field in the DTO ? #740

Closed jky0ung closed 1 week ago

jky0ung commented 1 month ago

I am encountering an error when trying to sort by a field in the DTO.

val salesSummaries = repository.findAll {
    selectNew<SalesSummary>(
        path(Transaction::date),
        count(caseWhen(path(Transaction::paymentMethod).equal("cash")).then(1)),
        sum(caseWhen(path(Transaction::paymentMethod).equal("cash")).then(path(Transaction::amount))),
        count(caseWhen(path(Transaction::paymentMethod).equal("card")).then(1)),
        sum(caseWhen(path(Transaction::paymentMethod).equal("card)).then(path(Transaction::amount))),
        count(path(Transaction::id)),
        sum(path(Transaction::amount)),
    )
    .from(entity(Transaction::class))
    .whereAnd(
        path(Transaction::date).between(start, end),
        shopCode?.let { path(Transaction::shopCode).equal(shopCode) }
    )
    .groupBy(path(Transaction::date))
    .orderBy(path(SalesSummary::totalAmount).desc()) // Need to sort!
}

Question

How can I sort by a field in the DTO?

The current code results in the following error:

Caused by: org.hibernate.query.SemanticException: Could not interpret path expression 'SalesSummary.totalAmount'

I would appreciate any guidance or suggestions on how to resolve this issue.

shouwn commented 1 month ago

SalesSummary cannot be used inside a query because it is a type of query result. For this reason, you must use sum(caseWhen(path(Transaction::paymentMethod).equal("cash")).then(path(Transaction::amount))) or sum(caseWhen(path(Transaction::paymentMethod).equal("card)).then(path(Transaction::amount))).

shouwn commented 1 week ago

This issue seems to be resolved, so I'll close it.