hibernatejpahqljpqlejbql

How to select the sum of multiple count() selections in JPQL


What's the equivalent JQPL statement of the following SQL statement:

SELECT (SELECT COUNT(*) FROM foo) + (SELECT COUNT(*) FROM bar)

Solution

  • You can use the query you stated above along with EntityManager's createNativeQuery function see example class below:

    package facades;
    
    import javax.ejb.LocalBean;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    
    @Stateless
    @LocalBean
    public class CustomFacade {
    
        @PersistenceContext(unitName = "TestJPQLPU")
        private EntityManager em;
    
        public CustomFacade(){}
    
        /**
         * Gets the count of all records in tables foo and bar.
         * @return number of records as Long.
         */
        public Long getCountOfObjects(){    
            Query countQuery = em.createNativeQuery("SELECT((SELECT COUNT(*) FROM Foo) + (SELECT COUNT(*) FROM Bar))");
            Long count = (Long) countQuery.getSingleResult();        
            return count;
        }
    }