Can we use projections with spring data base methods or not?

103 Views Asked by At

I was reading the spring doc about projections :

https://docs.spring.io/spring-data/jpa/reference/repositories/projections.html

when I came across this note

Declaring a method in your Repository that overrides a base method (e.g. declared in CrudRepository, a store-specific repository interface, or the Simple…Repository) results in a call to the base method regardless of the declared return type. Make sure to use a compatible return type as base methods cannot be used for projections. Some store modules support @Query annotations to turn an overridden base method into a query method that then can be used to return projections.

The problem is just above it they are using it with a base method

interface PersonRepository extends Repository<Person, UUID> {
          Collection<NamesOnly> findByLastname(String lastname);}

PS: I know that projections alter the SQL queries sent to database to only retrieve the columns we want, does this mean that if we use projections with base methods it will get all the columns of the object then project it in java or what?

I searched but didn't find any resources that can help, since the confusion came from the docs itself

1

There are 1 best solutions below

1
On

If you need to customize the data that is returned from the overridden method, you can use the @Query annotation to create a custom query method. The @Query annotation allows you to specify a JPQL or native SQL query that will be executed to retrieve the desired data. Here is an exmaple of how you can do it

@Repository
public interface MyEntityRepository extends CrudRepository<MyEntity, 
Long> {
@Query("SELECT e.id, e.name FROM MyEntity e WHERE e.id = ?1")
MyEntityProjection findByIdProjection(Long id);
}