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.
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:
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:
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:
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:
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
| Technique | Description | Type Safety | Flexibility |
| JPQL Queries | Simple string-based queries | Low | High (manual) |
| Criteria API | Type-safe API for dynamic queries | High | High |
| Interface Projections | Spring Data JPA automatically implements the interfaces | High | Medium (limited custom logic) |
| DTO Projections | Strong typing with advanced mapping logic | High | Medium (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
- Spring nested transactions
- Spring @Transactional - isolation, propagation
- springboot 2.3.0 while connecting to h2 database
- SpringBoot doesn't handle org.hibernate.exception.ConstraintViolationException
- Spring Kafka- When is exactly Consumer.poll() called behind the hood?
- Spring Kafka - Consume last N messages for partitions(s) for any topic
- SpringBoot error Registered driver with driverClassNameoracle.jdbc.driver.OracleDriver was not found, trying direct instantiation
- Springboot org.hibernate.MappingException Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack 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.