Spring JPA data specification for selecting specific columns

We can select specific columns by writing custom @Query methods in our repository interface. However, I do not want to write so many methods for different properties.

I tried this, but it always returns the whole object.

public class MySpecifications { public static Specification<MyInfo> propertiesWithId(final String[] properties, final Object id, final String idProperty) { return new Specification<MyInfo>() { @Override public Predicate toPredicate(Root<MyInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) { query = cb.createTupleQuery(); //tried cb.createQuery(MyInfo.class); as well List<Selection<? extends Object>> selectionList = new ArrayList<Selection<? extends Object>>(); for (String property : properties) { Selection<? extends Object> selection = root.get(property); selectionList.add(selection); } return query.multiselect(selectionList).where(cb.equal(root.get(idProperty), id)).getRestriction(); } }; } } 

used as:

 MyInfo findOne(Specification(properties,idValue, idProperty)); 

Is it correct? Where is the mistake?

+7
java spring spring-data spring-data-jpa jpa
source share
2 answers

In the current jpa spec specifier, the spring spec is limited to the criteria in the where clause, so you can modify the selected columns, limited to entities only. You will have to go with the custom implementation of the repository or go to named queries -

Spring JPA and Querydsl data to retrieve a subset of columns using a bean / constructor

+1
source share

I tried this, but it always returns the whole object.

This method returns a single entity that matches the specified specification. Please check here

In my opinion, this is the right way. U can access object properties as usual (e.g. MyInfo.getIdProperty ())

0
source share

All Articles