3

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

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

1 回答 1

1

您可以将上述查询与EntityManager 的 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;
    }
}
于 2012-05-15T16:25:00.773 回答