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. 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.
You can also use the @EntityGraph
annotation to specify which attributes should be fetched when executing the query. This can be more efficient than specifying the columns in the SELECT
clause, as it allows the JPA implementation to use a single query to fetch the required data, rather than multiple queries.
Here's an example of using @EntityGraph
to select specific columns:
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@EntityGraph(attributePaths = {"id", "username"})
List<User> findAll();
}
In this example, the findAll
method will return a list of User
entities, but only the id
and username
attributes will be fetched from the database.