简体   繁体   中英

How to join two Criteria Queries

I have a query that I want to make Criteria Query

select u.email, st.total_amount, st.company_total  from users u
join (select user_id, SUM(balance) as total_amount,SUM(company_count) as company_total from subscription s
      where s.is_active = 0
group by user_id) st on u.id = st.user_id 
where u.is_active = 0
order by st.company_total 

I have already made 1 criteria Query

CriteriaQuery<UserImpl> innerQuery = builder.createQuery(UserImpl.class);
            Root<Subscription> subscriptionRoot = innerQuery.from(Subscription.class);
            innerQuery.multiselect(subscriptionRoot.get("user").get("id"), builder.sum(subscriptionRoot.get("balance")),
                    builder.sum(subscriptionRoot.get("companyCount")));

I don't know how to make the outer query in spring hibernate JPA. Can some help.

Defining a JOIN clause is pretty simple. You first call the from method on your CriteriaQuery object to get a Root object. In the next step, you can call the join method to define your JOIN clause.

Following is example of Docs, you can manipulate it as per your example.

You can refer Hibernate docs for the join examples. following is sample code.

CriteriaQuery<String> q = cb.createQuery(String.class);
Root<Order> order = q.from(Order.class);
q.select(order.get("shippingAddress").<String>get("state"));

CriteriaQuery<Product> q2 = cb.createQuery(Product.class);
q2.select(q2.from(Order.class)
                 .join("items")
                 .<Item,Product>join("product"));

Docs to refer

Another quick example I found is listed below:

<Y> ListJoin<X, Y> join(ListAttribute<? super X, Y> list);

Quick example (assuming Employee has list of Tasks with many-to-many relation):

CriteriaQuery<Employee> query = criteriaBuilder.createQuery(Employee.class);
Root<Employee> employee = query.from(Employee.class);
ListJoin<Employee, Task> tasks = employee.join(Employee_.tasks);
query.select(employee)
        .where(criteriaBuilder.equal(tasks.get(Task_.supervisor), 
employee.get(Employee_.name)));
TypedQuery<Employee> typedQuery = entityManager.createQuery(query);
List<Employee> employees = typedQuery.getResultList();

Reference: here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM