javaspringspring-boothibernatespring-data-jpa

SELECT clause in JPA Query Methods


In Spring JPA's Query Methods, we can specify the WHERE clause but how can I specify the SELECT clause without using the @Query annotation? What I mean is:

I have an entity User with properties ProfilePhoto profilePhoto and String email:

@Entity
class User {
    ...

    @OneToOne
    ProfilePhoto profilePhoto;
    
    @Column(unique = true, nullable = false)
    String email;
    
    ...
}

@Entity
class ProfilePhoto {
    ...
    Integer id;
    String url;
    ...
}

So using the JPA Repository's Query Methods I can make queries like this:

User findById(Integer id);
User findByEmail(String email);
User findByProfilePhoto_Id(String profilePhotoId);

But not like this:

String findEmailById(Integer id);
ProfilePhoto findProfilePhotoById(Integer id);
String findProfilePhoto_UrlById(Integer id);

This can be done using the @Query annotation but that is not so desirable for me.


Solution

  • You can use something called 'Projections' which lets you do exactly this.

    Create a separate interface :

    public interface UserProjections {
        String getEmail();
    }
    

    Use this in your repository :

    interface UserRepository extends Repository<User, UUID> {
           
        // Usual methods
        User findById(Integer id);
        User findByEmail(String email);
        User findByProfilePhoto_Id(String profilePhotoId);
    
        // unusual method
        Collection<UserProjections> findEmailById(String id);
    
    }
    

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