Search code examples
javajpaspring-data-jpa

Spring JPA selecting specific columns


I am using Spring JPA to perform all database operations. However I don't know how to select specific columns from a table in Spring JPA?

For example:
SELECT projectId, projectName FROM projects


Solution

  • You can set nativeQuery = true in the @Query annotation from a Repository class like this:

    public static final String FIND_PROJECTS = "SELECT projectId, projectName FROM projects";
    
    @Query(value = FIND_PROJECTS, nativeQuery = true)
    public List<Object[]> findProjects();
    

    Note that you will have to do the mapping yourself though. It's probably easier to just use the regular mapped lookup like this unless you really only need those two values:

    public List<Project> findAll()
    

    It's probably worth looking at the Spring data docs as well.