skip to Main Content

Currently, while a project using Spring is in progress, DB search using JDBC template is being modified to use JPA.
In this situation, it is burdensome to use the JAP repository, so I want to use the entity manager.
I want to get max value of Score using entity manager.

When I run the code below, I want to output the score of the item with the highest score among the items with that ID.

    public Integer findByTraceId(String id) {
        String jpql = "SELECT MAX(Score) FROM item where id = :id";
        TypedQuery<Integer> query = em.createQuery(jpql, Integer.class);
        query.setParameter("id", id);
        return query.getResultList().get(0);
    }

2

Answers


  1. You can try that "SELECT MAX(i.Score) FROM item i where i.id = :id";

    Login or Signup to reply.
  2. You may use the following query which employs a subquery to find the max score for a given item:

    SELECT i1
    FROM item i1
    WHERE i1.Score = (SELECT MAX(i2.Score) FROM item i2 WHERE i2.id = :id)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search