Search code examples
javadatabasejpajpql

How to find first in JPQL


I have a query to find if a value already exists within the database. I am using it to validate a resource before it is inserted onto the database. it looks like this:

  @NamedQuery(name = "findByName", query = "SELECT g FROM Group g where g.value= :value")

and on the data access the implementation is as follows:

final TypedQuery<Group> query = entityManager.createNamedQuery("findByName", Group.class);
    query.setParameter("value", value);
    return !query.getResultList().isEmpty();

It does work and does the job, however I think that query.getResultList().isEmpty() is not the right syntax that I need plus I was looking to make it faster and return once the value is found rather than looping through every row on the database. Any suggestions will be appreciated.


Solution

  • What about:

     @NamedQuery(name = "existsByName", query = "SELECT CASE WHEN COUNT(g) > 0 THEN true ELSE false END FROM Group g where g.value= :value")
    
    boolean exists = entityManager.createNamedQuery("existsByName",Boolean.class).setParameter("value",value).getSingleResult();