Search code examples
javapostgresqleclipselinkjpqlpayara-micro

Is there a way to prevent JPQL's FUNCTION from returning an object of type java.lang.Object?


I have the following JPQL query running in a Payara Micro 5.2022.2 application.

TypedQuery<UserDto> query = entityManager.createQuery(
    "SELECT new UserDto((FUNCTION('COALESCE', (select fullname from Person p where p.userId = u.id), 'Name not set'))) " + 
    " FROM User u WHERE u.id = :userId", User.class);
query.setParameter("userId", 12);
return query.getResultList();

The type of the field is returned as java.lang.Object and not as java.lang.String since the column, fullname is varchar in it's table.

This forces me to have the constructor to have an Object parameter and not String

I wanted to find out if there is a way to get this code (FUNCTION('COALESCE', (select fullname from Person p where p.userId = u.id), 'Name not set'))) to return a String and not an Object


Solution

  • As per Andrey B. Panfilov's comment, I had to cast the return value to a String:

    TypedQuery<UserDto> query = entityManager.createQuery(
        "SELECT new UserDto(CAST(FUNCTION('COALESCE', (select fullname from Person p where p.userId = u.id), 'Name not set') as text)) " + 
        " FROM User u WHERE u.id = :userId", User.class);
    query.setParameter("userId", 12);
    return query.getResultList();