Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA Specification to Select Specific Columns

We can select specific columns by writing custom @Query methods in our Repository Interface. However, I don't want to write so many methods for different properties.

I tried this, but it returns the entire object all the time.

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 this the correct way? Where is the mistake?

like image 980
Chinmay Avatar asked Mar 04 '14 12:03

Chinmay


People also ask

How do you select specific columns in criteria query?

One of the JPA ways for getting only particular columns is to ask for a Tuple object. then you can use T directly in your CriteriaQuery constructor: CriteriaQuery<T> cq = builder. createQuery(T.


Video Answer


1 Answers

The current spring data jpa specification executor is limited to criteria in the where clause, so you can't change the selected columns, it's implicitely limited to full entities only (take a look at JpaSpecificationExecutor interface documentation). You'll have to go with a custom repository implementation, or move to named queries-

Spring Data JPA and Querydsl to fetch subset of columns using bean/constructor projection

like image 169
chrismarx Avatar answered Sep 19 '22 09:09

chrismarx