Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDsl - subquery in collection expression

I'm using spring-data-jpa and querydsl (3.2.3)
I have a scenario where I'm creating set of predicates based on user filer/input. All of these comes to BooleanExpression.

My simplified model looks as following:

@Entity
public class Invoice {
    @ManyToOne
    private Supplier supplier;
}

@Entity
public class Supplier {
    private String number;
}

@Entity
public class Company {
    private String number;
    private boolean active
}

Now, what I'm struggling with is this query:

SELECT * FROM Invoice WHERE invoice.supplier.number in (SELECT number from Company where active=true)

So basically I need to subquery in CollectionExpression like format that will fetch all companies numbers and sets this into in() expression.

My spring-data repositories implements CustomQueryDslJpaRepository which in turn extends JpaRepository and QueryDslPredicateExecutor.
I hope the answer to this is straightforward, but I'm quite new to querydsl and didn't find the solutions so far.

like image 374
wiecia Avatar asked Feb 17 '14 10:02

wiecia


People also ask

How do I write a subquery in Querydsl?

Subqueries To create a subquery you create a JPASubQuery instance, define the query parameters via from, where etc and use unique or list to create a subquery, which is just a type-safe Querydsl expression for the query. unique is used for a unique (single) result and list for a list result.

What is Querydsl in Java?

Querydsl is an extensive Java framework, which allows for the generation of type-safe queries in a syntax similar to SQL. It currently has a wide range of support for various backends through the use of separate modules including JPA, JDO, SQL, Java collections, RDF, Lucene, Hibernate Search, and MongoDB.

What is Querydsl spring?

Querydsl is a framework that enables the construction of statically typed SQL-like queries through its fluent API. Spring Data modules offer integration with Querydsl through QuerydslPredicateExecutor .


2 Answers

Here is a variant of jaiwo99's answer in a more JPAesque form

BooleanExpression exp = invoice.supplier.number.in(new JPASubQuery()
    .from(company)
    .where(company.active.isTrue())
    .list(company.nu‌​mber));

Feel free to merge this into the original answer.

like image 109
Timo Westkämper Avatar answered Sep 19 '22 08:09

Timo Westkämper


Try this:

QInvoice invoice = QInvoice.invoice;
QCompany company = QCompany.company;

List<Invoice> list = new HibernateQuery(sessionFactory.getCurrentSession())
      .from(invoice).where(
      new HibernateSubQuery().from(invoice, company).where(
              invoice.supplier.number.eq(company.number).and(
              company.active.eq(true))).exists()).list(invoice);
like image 29
Jaiwo99 Avatar answered Sep 19 '22 08:09

Jaiwo99