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
Some time case arises, where we need a custom query to fulfil one test case. We can use @Query annotation to specify a query within a repository.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With