0 day streak
java / intermediate
Snippet

Fetching Partial Data using Interface Projections

Spring Data JPA allows you to define interfaces to retrieve only a subset of fields from a database entity. This is more efficient than loading the full entity when only a few fields are needed, especially for UI lists.

snippet.java
java
1
2
3
4
5
6
7
8
9
public interface UserSummary {
String getUsername();
@Value("#{target.firstName + ' ' + target.lastName}")
String getFullName();
}
public interface UserRepository extends JpaRepository<User, Long> {
List<UserSummary> findAllByActiveTrue();
}
spring
Breakdown
1
public interface UserSummary
The projection interface defines the getter methods for the fields you want to retrieve.
2
@Value("#{...}")
Uses SpEL (Spring Expression Language) to compute a virtual property from entity fields.
3
List<UserSummary>
Tells Spring Data to proxy the result into the interface rather than returning Entity objects.