W3docs

Spring JPA selecting specific columns

To select specific columns using Spring JPA, you can use the @Query annotation and specify the columns in the SELECT clause of the JPQL query.

To select specific columns using Spring JPA, you can use the @Query annotation and specify the columns in the SELECT clause of the JPQL query. Here's an example:


@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u.id, u.username FROM User u")
    List<Object[]> findAllProjectedBy();
}

In this example, the findAllProjectedBy method will return a list of arrays, each array containing the id and username of a User entity.

Alternatively, Spring Data JPA provides interface-based projections and constructor expressions, which are the standard approaches for mapping specific columns to DTOs without returning raw arrays. Note that @EntityGraph is designed to optimize the fetching of entity associations, not to reduce the columns in the SELECT clause.

Interface-based projection

public interface UserSummary {
    Long getId();
    String getUsername();
}

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    List<UserSummary> findAllProjectedBy();
}

Spring Data JPA automatically implements the UserSummary interface based on the method name.

Constructor expression

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT new com.example.UserDto(u.id, u.username) FROM User u")
    List<UserDto> findAllProjectedBy();
}

This requires a matching constructor in the UserDto class.