Hello I try to convert a jpql query to the criteria api.
the sql query is
SELECT COUNT(DISTINCT id) FROM `user` WHERE login != :anonymousUser
I've just succeed to reach this query with criteria
SELECT COUNT(id) FROM `user` WHERE login != :anonymousUser
here is the code:
class UserRepository(
private val repo: R2dbcEntityOperations
) {
companion object {
@JvmStatic
private val userModel by lazy { User::class.java }
}
// expected query:
//"SELECT COUNT(DISTINCT id) FROM `user` WHERE login != :anonymousUser"
fun countAllByLoginNot(anonymousUser: String): Mono<Long> {
return repo.select(userModel)
//current query:
//"SELECT COUNT(id) FROM `user` WHERE login != :anonymousUser"
.matching(
query(
where("login")
.not(anonymousUser).ignoreCase(true)
)
)
.count()
}
}
How do I introduce the distinct with criteria API?
I've been plagued with similar problems. Although I'm using java, I seem to have found something relevant that I hope will help you:
If you want to de-duplicate the count function, you may need to refer to
org.springframework.data.relational.core.sql.SimpleFunctionto implement a new class, such asCountDistinctFunction. You can refer to this:And use it:
Although this post has been a long time coming, I'll give my opinion on it. If anyone happens to see it and has a better plan, then please let me know too, thanks a lot!
(Translated via DeepL)