Advertisement
Google Ad Slot: content-top
Spring Boot JPA Projection (Fetching Specific Columns)
Projection in Spring Boot JPA allows you to fetch specific columns from a table instead of the entire entity. This improves performance by reducing data transfer.
Using Interface-Based Projection
The simplest way to fetch specific columns is by defining an interface projection
Example: Fetching Only id and name from User
✅ Advantage:Faster than fetching the entire entity.
Using JPQL with Projection
If you need custom queries, you can use JPQL.
✅ Advantage: More flexible, can handle complex queries.
Using DTO (Data Transfer Object) Projection
Example: Fetching id, name, and age into a DTO
✅ Advantage: Works well with custom DTO transformations.
Native SQL Queries with Projection
If you need raw SQL, use @Query(nativeQuery = true).
✅ Advantage: Ideal for complex SQL queries with joins, group by, etc.