如何使用Criteria Clause进行JPA查询?

时间:2013-01-05 01:03:38

标签: java jpa pagination criteria-api

首先,我想进行像

这样的查询
"select count(*) from Post p where p.tag in (tagArray) "

其中tagArray是“'tag1','tag2','tag3'”。然后我想做一个分页查询:

query.setFirstResult(int1).setMaxResult(int2);

我不知道如何编写此查询。我搜索了帖子,找不到答案,那么有人可以给我任何建议吗?感谢。

2 个答案:

答案 0 :(得分:2)

以下是示例代码:

// get an entity manager
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpaManager");
EntityManager em = emf.createEntityManager();
// create query
Query query = em.createQuery("select count(*) from Post p where p.tag in (tagArray)") // use parameters here when necessary 
            .setFirstResult(int1)
            .setMaxResults(int2);
// get result
query.getResultList();

更新

如果您想按条件创建查询,请尝试以下方法:

CriteriaBuilder builder = em.getCriteriaBuilder(); // em is as the same the the above
CriteriaQuery<Post> query = builder.createQuery(Post.class);
Root<Post> post = query.from(Post.class);
query.select(post).where(post.get("tag").in("tag1", "tag2", "tag3")); // or pass a tag collection to `in` method
TypedQuery<Post> typedQuery = em.createQuery(query);
List<Post> results = typedQuery.setFirstResult(int1).setMaxResults(int2)
                     .getResultList();

答案 1 :(得分:0)

非常感谢!按照你的指示,我这样做了,有点复杂。

    public List<Post> findPostBySitePaged(Set sites, Page page) {
    List<Post> result = new ArrayList<Post>();
    if (sites == null || sites.size() == 0) return result;

    try {
        CriteriaBuilder builder = em.getCriteriaBuilder();

        CriteriaQuery<Long> cQuery = builder.createQuery(Long.class);
        Root<Post> root = cQuery.from(Post.class);

        CriteriaQuery<Long> select = cQuery.select(builder.count(root));
        select.where(root.get("site").in(sites));

        TypedQuery<Long> typedQuery = em.createQuery(select);
        Long t = typedQuery.getSingleResult();

        int tot = t.intValue() / page.getPageSize() + ((t.intValue() % page.getPageSize()) == 0 ? 0 : 1);
        page.setTotal(tot);

        CriteriaQuery<Post> criteriaQuery = builder.createQuery(Post.class);
        root = criteriaQuery.from(Post.class);
        criteriaQuery.select(root).where(root.get("site").in(sites)).orderBy(builder.desc(root.get("createDate")));

        TypedQuery<Post> postQuery = em.createQuery(criteriaQuery);
        postQuery.setFirstResult((page.getCurrent() - 1) * (page.getPageSize())).setMaxResults(page.getPageSize());

        result = postQuery.getResultList();

    } catch (Exception e) {
        log.error(e.getMessage());
    }

    return result;
}