Skip to content
Advertisement

JPQL query that give me the highest value

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 🙂

Advertisement

Answer

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;
    }
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement