Friday, 15 May 2015

A Cleaner Entity Count

Using TypedQuery<T> I got a cleaner entity count with JPA's JPQL.

Here is the cleaner way:

    public int countAllMessages(){
        return em.createQuery("SELECT count(m) FROM Message m", Number.class).getSingleResult().intValue();
    }

Instead of:

    public int countAllMessages(){
        Query q = em.createQuery("SELECT count(m) FROM Message m");
        Number result = (Number) q.getSingleResult();
        return result.intValue();
    }

Where q.getSingleResult() is cast to Number.

No comments:

Post a Comment