return null on quarkus hibernate orm no result

275 views Asked by At

I am working on a project where I am using the Quarkus Hibernate ORM and running queries like the code below. Every time a query fails to find an entity, it throws a 500 error:

fun getByEmail(email: String): MutableList<Any?> {
    return try {
    em.createQuery("SELECT u FROM User u WHERE u.email = :email").setParameter("email", email).resultList
    } catch (e: Throwable) {
        mutableListOf()
    }
}

It is quite annoying to use a try catch every time the EM is used.

My question is if there is a way to disable the NoResultError and instead return null or in this case an empty list?

I tried to disable the error in my application.properties, but it did not work.

quarkus.hibernate-orm.returning-null-on-no-result=true

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-orm-panache-kotlin</artifactId>
</dependency>

<dependency>
     <groupId>io.quarkus</groupId>
     <artifactId>quarkus-jdbc-mariadb</artifactId>
</dependency>
1

There are 1 answers

0
yrodiere On

You shouldn't be getting a NoResultException when calling getResultList(); if you do, please open a bug report to Quarkus with a reproducer.

I suspect your actual code uses getSingleResult() instead? That's the only method that throws a NoResultException in the Hibernate ORM codebase.

If so, just use Hibernate ORM's Session to create your query and you'll be able to use uniqueResult() or uniqueResultOptional().

Not sure how to do that in Kotlin, but I imagine something like this could work?

fun getByEmail(email: String): Any? {
    return session.createQuery("SELECT u FROM User u WHERE u.email = :email").setParameter("email", email).uniqueResult()
}

EDIT: and it would be even simpler if you were actually using Panache, something like:

fun getByEmail(email: String): User? {
    return User.find("email", email).firstResult()
}