Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 291
Wil Ferraciolli Avatar asked Sep 13 '25 02:09

Wil Ferraciolli


1 Answers

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();
like image 133
Roma Khomyshyn Avatar answered Sep 14 '25 17:09

Roma Khomyshyn