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
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
In my opinion this is great solution:
and using it like so
You can use JPQL:
or you can use native sql query.
You can apply the below code in your repository interface class.
In my case i created a separate entity class without the fields that are not required (only with the fields that are required).
Map the entity to the same table. Now when all the columns are required i use the old entity, when only some columns are required, i use the lite entity.
e.g.
You can create something like :
This works when you know the columns to fetch (and this is not going to change).
won't work if you need to dynamically decide the columns.
In my situation, I only need the json result, and this works for me:
in Controller:
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):
Then of course, you just have to provide a constructor for Document that accepts docId & filename as constructor args.