Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting fields on Spring Data

I'm trying to find information about how to select only certain fields of an entity using Spring Data (I'm using JPA). I want to select only specific information of an entity, the repository interfaces gives you the ways to return the information of the WHOLE entity!. Some times I only need 2 or 3 fields of an entity and returning 20,30, ...100.. fields may be a little overkill.

This kind of functionality is something that I would do using Hibernate Criteria Projections, or even JPA "SELECT NEW ...." queries. Don't know if it is possible with Spring Data.

Thanks.

like image 814
yagamipaul Avatar asked Nov 08 '12 13:11

yagamipaul


2 Answers

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

@Query("select el.moduleId, el.threadId from ExceptionLog el")
public List<Object[]> tempQuery();
like image 87
Parvez Avatar answered Oct 27 '22 10:10

Parvez


I think you can also do it in this way

SomeDataPOJO{
    required col1
    required col2
}

and then write query like this

@Query("select new SomeDataPOJO from requiredTable where xyz="abc")
public List<SomeDataPoJO> tempQuery()
like image 43
Vipul Jain Avatar answered Oct 27 '22 09:10

Vipul Jain