Spring JPA selecting specific columns Spring JPA selecting specific columns java java

Spring JPA selecting specific columns


You can use projections from Spring Data JPA (doc). In your case, create interface:

interface ProjectIdAndName{    String getId();    String getName();}

and add following method to your repository

List<ProjectIdAndName> findAll();


I don't like the syntax particularly (it looks a little bit hacky...) but this is the most elegant solution I was able to find (it uses a custom JPQL query in the JPA repository class):

@Query("select new com.foo.bar.entity.Document(d.docId, d.filename) from Document d where d.filterCol = ?1")List<Document> findDocumentsForListing(String filterValue);

Then of course, you just have to provide a constructor for Document that accepts docId & filename as constructor args.


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.