DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Connection Pooling
  • How To Convert MySQL Database to SQL Server
  • Navigating NoSQL: A Pragmatic Approach for Java Developers
  • Making Spring AI and OpenAI GPT Useful With RAG on Your Own Documents

Trending

  • Demystifying Databases, Data Warehouses, Data Lakes, and Data Lake Houses
  • Demystifying Static Mocking With Mockito
  • 5 Steps To Tame Unplanned Work
  • Testing Swing Application
  1. DZone
  2. Data Engineering
  3. Databases
  4. JPA - Querydsl Projections

JPA - Querydsl Projections

Michal Jastak user avatar by
Michal Jastak
·
May. 15, 13 · Interview
Like (3)
Save
Tweet
Share
36.7K Views

Join the DZone community and get the full member experience.

Join For Free

In my last post: JPA - Basic Projections - I've mentioned about two basic possibilities of building JPA Projections. This post brings you more examples, this time based on Querydsl framework. Note, that I'm referring Querydslversion 3.1.1 here.

Reinvented constructor expressions


Take a look at the following code:...

import static com.blogspot.vardlokkur.domain.QEmployee.employee;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import com.blogspot.vardlokkur.domain.EmployeeNameProjection;
 
import com.mysema.query.jpa.JPQLTemplates;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.ConstructorExpression;
...
 
public class ConstructorExpressionExample {
    
    ...
    @PersistenceContext
    private EntityManager entityManager;
 
    @Autowired
    private JPQLTemplates jpqlTemplates;
    
    public void someMethod() {
        ...
        final List<EmployeeNameProjection> projections = new JPAQuery(entityManager, jpqlTemplates)
                        .from(employee)
                        .orderBy(employee.name.asc())
                        .list(ConstructorExpression.create(EmployeeNameProjection.class, employee.employeeId,
                                        employee.name));
        ...                                
    }
    ...
}

The above Querydsl construction means: create new JPQL query [1][2], using employee as the data source, order the data using employee name [3], and return the list of EmployeeNameProjection, built using the 2-arg constructor called with employee ID and name [4].  This is very similar to the constructor expressions example from my previous post (JPA - Basic Projections), and leads to the following SQL query:

select EMPLOYEE_ID, EMPLOYEE_NAME from EMPLOYEE order by EMPLOYEE_NAME asc
As you see above, the main advantage comparing to the JPA constructor expressions is using Java class, instead of its name hard-coded in JPQL query.

Even more reinvented constructor expressions


Querydsl documentation [4] describes another way of using constructor expressions, requiring @QueryProjectionannotation and Query Type [1] usage for projection, see example below. Let's start with the projection class modification - note that I added @QueryProjection annotation on the class constructor.
package com.blogspot.vardlokkur.domain;
 
import java.io.Serializable;
 
import javax.annotation.concurrent.Immutable;
 
import com.mysema.query.annotations.QueryProjection;
 
@Immutable
public class EmployeeNameProjection implements Serializable {
 
    private final Long employeeId;
 
    private final String name;
 
    @QueryProjection
    public EmployeeNameProjection(Long employeeId, String name) {
        super();
        this.employeeId = employeeId;
        this.name = name;
    }
 
    public Long getEmployeeId() {
        return employeeId;
    }
 
    public String getName() {
        return name;
    }
 
}
Now we may use modified projection class (and corresponding Query Type [1] ) in following way:
...
import static com.blogspot.vardlokkur.domain.QEmployee.employee;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import com.blogspot.vardlokkur.domain.EmployeeNameProjection;
import com.blogspot.vardlokkur.domain.QEmployeeNameProjection;
 
import com.mysema.query.jpa.JPQLTemplates;
import com.mysema.query.jpa.impl.JPAQuery;
 
...
 
public class ConstructorExpressionExample {
    ...
    @PersistenceContext
    private EntityManager entityManager;
 
    @Autowired
    private JPQLTemplates jpqlTemplates;
 
    public void someMethod() {
        ...
        final List<EmployeeNameProjection> projections = new JPAQuery(entityManager, jpqlTemplates)
            .from(employee)
            .orderBy(employee.name.asc())
            .list(new QEmployeeNameProjection(employee.employeeId, employee.name));
        ...
    }
    ...
}
Which leads to SQL query:

select EMPLOYEE_ID, EMPLOYEE_NAME from EMPLOYEE order by EMPLOYEE_NAME asc
In fact, when you take a closer look at the Query Type [1] generated for EmployeeNameProjection(QEmployeeNameProjection), you will see it is some kind of "shortcut" for creating constructor expression the way described in first section of this post.

Mapping projection

Querydsl provides another way of building projections, using factories based on MappingProjection.
package com.blogspot.vardlokkur.domain;
 
import static com.blogspot.vardlokkur.domain.QEmployee.employee;
 
import com.mysema.query.Tuple;
import com.mysema.query.types.MappingProjection;
 
public class EmployeeNameProjectionFactory extends MappingProjection<EmployeeNameProjection> {
 
    public EmployeeNameProjectionFactory() {
        super(EmployeeNameProjection.class, employee.employeeId, employee.name);
    }
 
    @Override
    protected EmployeeNameProjection map(Tuple row) {
        return new EmployeeNameProjection(row.get(employee.employeeId), row.get(employee.name));
    }
 
}
The above class is a simple factory creating EmployeeNameProjection instances using employee ID and name. Note that the factory constructor defines which employee properties will be used for building the projection, and mapmethod defines how the instances will be created.

Below you may find an example of using the factory:
...
import static com.blogspot.vardlokkur.domain.QEmployee.employee;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
 
import org.springframework.beans.factory.annotation.Autowired;
 
import com.blogspot.vardlokkur.domain.EmployeeNameProjection;
import com.blogspot.vardlokkur.domain.EmployeeNameProjectionFactory
 
import com.mysema.query.jpa.JPQLTemplates;
import com.mysema.query.jpa.impl.JPAQuery;
...
 
public class MappingProjectionExample {
    
    ...
    @PersistenceContext
    private EntityManager entityManager;
 
    @Autowired
    private JPQLTemplates jpqlTemplates;
 
    public void someMethod() {
        ...
        final List<EmployeeNameProjection> projections = new JPAQuery(entityManager, jpqlTemplates)
                            .from(employee)
                            .orderBy(employee.name.asc())
                            .list(new EmployeeNameProjectionFactory());
        ....
    }
    ...
}
As you see, the one and only difference here, comparing to constructor expression examples, is the list method call.

Above example leads again to the very simple SQL query:

select EMPLOYEE_ID, EMPLOYEE_NAME from EMPLOYEE order by EMPLOYEE_NAME asc

Building projections this way is much more powerful, and doesn't require existence of n-arg projection constructor.

QBean based projection (JavaBeans strike again)


There is at least one more possibility of creating projection with Querydsl - QBean based - in this case we build the result list using:

... .list(Projections.bean(EmployeeNameProjection.class, employee.employeeId, employee.name))

This way requires EmployeeNameProjection class to follow JavaBean conventions, which is not always desired in application. Use it if you want, but you have been warned ;)

Few links for the dessert

  1. Using Query Types
  2. Querying
  3. Ordering
  4. Constructor projections


Database

Published at DZone with permission of Michal Jastak, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Connection Pooling
  • How To Convert MySQL Database to SQL Server
  • Navigating NoSQL: A Pragmatic Approach for Java Developers
  • Making Spring AI and OpenAI GPT Useful With RAG on Your Own Documents

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: