java / intermediate
Snippet
Interface-based Projections in Spring Data JPA
Projections allow you to fetch only specific fields from the database instead of loading entire entities. This reduces memory usage and improves database performance by selecting only needed columns.
snippet.java
1
2
3
4
5
6
7
8
9
public interface UserSummary {String getName();@Value("#{target.firstName + ' ' + target.lastName}")String getFullName();}public interface UserRepository extends JpaRepository<User, Long> {List<UserSummary> findByLastName(String lastName);}
spring
Breakdown
1
UserSummary
An interface defining getter methods for the fields to be retrieved.
2
@Value
Uses SpEL (Spring Expression Language) to compute a value from multiple entity fields.
3
List<UserSummary>
The repository returns a list of projection instances instead of entity objects.