如何在JPQL中选择多个count()选项的总和

时间:2012-04-26 07:18:33

标签: hibernate jpa hql jpql ejbql

以下SQL语句的等效JQPL语句是什么:

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

1 个答案:

答案 0 :(得分:1)

您可以使用上面提到的查询以及EntityManager's createNativeQuery函数,请参阅下面的示例类:

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