Selecting Fields in Spring Data

I am trying to find information on how to select only specific fields of an object using Spring Data (I use JPA). I want to select only specific information about the entity, the repository interfaces give you ways to return the information of the WHOLE! Object. In some cases, I need only 2 or 3 fields of the object, and 20,30, ... 100 .. the fields can be a bit crowded.

This functionality is what I would do using Hibernate Criteria Projections forecasts or even JPA "SELECT NEW ...." queries. I don't know if this is possible using Spring data.

Thanks.

+6
source share
2 answers

What you can do is return List<Object[]> from the repository. Then, in your service class, iterate over this list and manually create the object you need. Repository Method Example

 @Query("select el.moduleId, el.threadId from ExceptionLog el") public List<Object[]> tempQuery(); 
+3
source

I think you can also do it this way.

 SomeDataPOJO{ required col1 required col2 } 

and then write the query as follows

 @Query("select new SomeDataPOJO from requiredTable where xyz="abc") public List<SomeDataPoJO> tempQuery() 
+2
source

All Articles