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

穿精又带淫゛_ 提交于 2019-12-23 15:59:58

问题


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

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

回答1:


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;
    }
}


来源:https://stackoverflow.com/questions/10328868/how-to-select-the-sum-of-multiple-count-selections-in-jpql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!