Search code examples
hibernatenamed-query

Return a string result from a named query in hibernate


How to return String type result in a named query which is of type Query.... the code i tried

public String getTargetEmail(){
    Query query= em.createNamedQuery("BC_READ_SYSTEM_PROPERTIES_BY_NAME");
    return (String)query.toString();
}

but this return something else like org.hibernate.ejb.QueryImpl@3e4d072b


Solution

  • Calling toString on Query object, you just get a string representation of it. You need actually to execute the query like this

    return (String) query.getSingleResult();
    

    Ensure that the query always returns only one result, otherwise calling getSingleResult, will throw a NonUniqueResultException exception in case more one result that one is returned, or NoResultException in case no result is returned (check documentation here)