Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 244
user1817436 Avatar asked Feb 25 '14 07:02

user1817436


People also ask

How do I create a custom query in spring boot?

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.


2 Answers

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(); 
like image 110
mpr Avatar answered Oct 22 '22 18:10

mpr


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.

like image 27
jm0 Avatar answered Oct 22 '22 18:10

jm0