Skip to content
Advertisement

How to return boolean result from SQL count via JPQL

I have a simple problem with sql query. I need to get true or false, I have tried multiple methods, but without good result. This query returns 0 because I have zero records in database. Perhaps the condition should be adjusted. Thanks for all ideas.

public boolean getAnalysisByUserId(final Integer userId) {
    Objects.requireNonNull(userId, "Integer userId cannot be null.");

    final Query query = this.manager.createQuery("select count(a) from AnalysisRequest a where" + " a.userId = :userId",
        AnalysisRequest.class);

    query.setParameter("userId", userId);

    if (query.getSingleResult().equals(0)) {
      return false;
    }
    return true;
  }

Answer

Solved, thank you all.

public boolean getAnalysisByUserId(final Integer userId) {
    Objects.requireNonNull(userId, "Integer userId cannot be null.");

final Query query = this.manager
    .createNativeQuery("select count(a.id) from AnalysisRequest a where a.userId = ?1");
query.setParameter(1, userId);

final Long result = (Long) query.getSingleResult();

return result != null && result > 0;
 }
Advertisement