Home > OS >  JPQL query that give me the highest value
JPQL query that give me the highest value

Time:02-13

I'm trying to do a JPQL query that give me the highest PK of the PKs in my table (https://drive.google.com/file/d/1_kaklkKdCbhT0-byqCtz6HgfluKKp8J-/view?usp=sharing). Here is my query :

@Override
public int lireMaxPk(Class cl, String nomPkElement) throws MyDBException {
    int nb = 1;
    try {
        String jpql = "SELECT max(e) FROM "   cl.getSimpleName()   " e";
        Query query = em.createQuery(jpql);
        nb = (int) query.getSingleResult();
    } catch (Exception ex) {
        throw new MyDBException(SystemLib.getFullMethodName(), ex.getMessage());
    }
    return nb;
}

The error says that the syntax of my query is wrong. Can someone please help me ? Thank you for your help :)

CodePudding user response:

Max needs to specify field names instead of table aliases.

CodePudding user response:

Thank you for your comments ! It allowed me to solve my problem. I've indeed needed to get the int ID property of my entity class. Here is my function :

@Override
    public int lireMaxPk(Class cl, String nomPkElement) throws MyDBException {
        int nb = 1;
        try {
            String jpql = "SELECT max(e."   nomPkElement   ") FROM "   cl.getSimpleName()   " e";
            Query query = em.createQuery(jpql);
            nb = (int) query.getSingleResult();
        } catch (Exception ex) {
            throw new MyDBException(SystemLib.getFullMethodName(), ex.getMessage());
        }
        return nb;
    }
  • Related