Search code examples
javaexceptionjpanullpointerexceptioncriteria

Dynamic COUNT in JPA throws NullPointerException


My goal is to make a method with which I can retrieve the total number of rows from any table in my database.

This is what I have done:

ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
EM = ENTITY_MANAGER_FACTORY.createEntityManager();

public static long getRowCount(Root<?> root) {
    CriteriaBuilder cb = EM.getCriteriaBuilder();
    CriteriaQuery<Long> query = cb.createQuery(Long.class);

    root = query.from(root.getClass());
    query.select(cb.count(root));

    return EM.createQuery(query).getSingleResult();
}

This is how I call the method:

Root<PlacesEntity> placesRoot = null;
DbTools.getRowCount(placesRoot)

It is not working though, the method throws a NullPointerException at the line root = query.from(root.getClass());.


Solution

  • Try this (warning not tested):

    public static long getRowCount(Class<?> rootClass) {
        CriteriaBuilder cb = EM.getCriteriaBuilder();
        CriteriaQuery<Long> query = cb.createQuery(Long.class);
    
        Expression<?> root = query.from(rootClass);
        query.select(cb.count(root));
    
        return EM.createQuery(query).getSingleResult();
    }
    
    /*****/
    DbTools.getRowCount(PlacesEntity.class);
    

    Good luck!