Spring JPA
Querying Data
Select Statements
Database Columns
Java Programming

Spring JPA selecting specific columns

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Spring Data JPA (Java Persistence API) simplifies the implementation of data access layers by reducing the boilerplate code required and implementing domain-based development. One common requirement is to select specific columns from a database, optimizing performance and resource usage by fetching only necessary data. This article discusses techniques for selecting specific columns using Spring Data JPA, with a focus on using JPQL (Java Persistence Query Language), Criteria API, and projections.

Using JPQL to Select Specific Columns

JPQL is an object-oriented query language for JPA designed to combine the power of SQL with the concept of object-oriented programming. When you need to select specific columns in JPQL, you can craft a custom query in your repository:

java
1import org.springframework.data.jpa.repository.JpaRepository;
2import org.springframework.data.jpa.repository.Query;
3import org.springframework.stereotype.Repository;
4
5@Repository
6public interface UserRepository extends JpaRepository<User, Long> {
7    @Query("SELECT u.name, u.email FROM User u")
8    List<Object[]> findNamesAndEmails();
9}

The method findNamesAndEmails will return a list of Object[] where each Object[] holds the name and email of a user. Each object array element corresponds to the column specified in the SELECT clause. This is a straightforward approach but comes with the drawback of not returning strongly typed objects unless further processing is done.

Criteria API: Dynamic Query Building

The Criteria API is another way to construct SQL in a type-safe manner. It's particularly useful when building dynamic queries based on various runtime conditions:

java
1CriteriaBuilder cb = entityManager.getCriteriaBuilder();
2CriteriaQuery<Object[]> cq = cb.createQuery(Object[].class);
3Root<User> user = cq.from(User.class);
4cq.multiselect(user.get("name"), user.get("email"));
5TypedQuery<Object[]> query = entityManager.createQuery(cq);
6List<Object[]> results = query.getResultList();

This example demonstrates creating a query to select the name and email columns using Criteria API. It returns the results as a list of object arrays.

Projections: DTOs and Interfaces

Projections are a more advanced solution provided by Spring Data JPA for dealing with specific columns. This method involves creating an interface or a DTO (Data Transfer Object) to define how the data should be projected from the database.

Interface-based Projections

Create an interface with getter methods that correspond to the column names in the database entity:

java
1public interface UserNameAndEmail {
2    String getName();
3    String getEmail();
4}
5
6@Repository
7public interface UserRepository extends JpaRepository<User, Long> {
8    List<UserNameAndEmail> findProjectedBy();
9}

Spring Data JPA automatically implements the interface and returns the objects, allowing for very clean and type-safe code that directly maps to your database structure.

DTO Projections

Alternatively, you can use a DTO projection:

java
1public class UserDTO {
2    private String name;
3    private String email;
4
5    public UserDTO(String name, String email) {
6        this.name = this.name;
7        this.email = this.email;
8    }
9
10    // Getters and setters
11}
12
13@Repository
14public interface UserRepository extends JpaRepository<User, Long> {
15    @Query("SELECT new com.example.UserDTO(u.name, u.email) FROM User u")
16    List<UserDTO> findUserDTOs();
17}

This method initializes DTOs directly in the query, which can be more straightforward than interface-based projections when working with complex data.

Summary of Techniques for Selecting Specific Columns

TechniqueDescriptionType SafetyFlexibility
JPQL QueriesSimple string-based queriesLowHigh (manual)
Criteria APIType-safe API for dynamic queriesHighHigh
Interface ProjectionsSpring Data JPA automatically implements the interfacesHighMedium (limited custom logic)
DTO ProjectionsStrong typing with advanced mapping logicHighMedium (coding overhead)

Conclusion

Selecting specific columns using Spring Data JPA is an essential skill when aiming to optimize your application's performance. Each method: JPQL, Criteria API, and projections, offers different strengths and weaknesses, affecting flexibility, type safety, and coding overhead. The best choice depends on specific use cases, such as the need for dynamic queries, the complexity of the resulting mappings, or the necessity of type-safe results.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.