如何在JPA Criteria查询API中编写自定义查询作为根?

问题描述 投票:0回答:1

我的查询是:

select * from tbl1 t1,
(select max(modified_datetime),id as ID ,status from 
 tbl2 group by modified_datetime,ID,status) t2 
where 
t1.ID=t2.ID;

我该如何实现?

请帮助!

hibernate jpa criteria-api
1个回答
0
投票

没有提供代码,我假设您已完成所有配置。以下是为您提供的解决方案。

@Query(nativeQuery = true, value = "select * from tbl1 t1,(select max(modified_datetime),id as ID ,status from tbl2 group by modified_datetime,ID,status) t2 where t1.ID=t2.ID;")
    ReturnType methodName(@Param("paramsHereIfAny") String paramsHereIfAny);

评论后编辑

//some parameters to your method
        String param1 = "1";
        String paramNull = null;

        CriteriaBuilder qb = em.getCriteriaBuilder();
        CriteriaQuery cq = qb.createQuery();
        Root<A> customer = cq.from(A.class);

        //Constructing list of parameters
        List<Predicate> predicates = new ArrayList<Predicate>();

        //Adding predicates in case of parameter not being null
        if (param1 != null) {
            predicates.add(
                    qb.equal(customer.get("someAttribute"), param1));
        }
        if (paramNull != null) {
            predicates.add(
                    qb.equal(customer.get("someOtherAttribute"), paramNull));
        }
        //query itself
        cq.select(customer)
                .where(predicates.toArray(new Predicate[]{}));
        //execute query and do something with result
        em.createQuery(cq).getResultList();
© www.soinside.com 2019 - 2024. All rights reserved.