2014-03-04 242 views
7

我們可以通過在我們的Repository Interface中編寫自定義的@Query方法來選擇特定的列。但是,我不想爲不同的屬性編寫這麼多的方法。Spring Data JPA Specification to Select Specific Columns

我試過了,但它一直返回整個對象。

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(); 
      } 

     }; 
    } 
} 

用作:

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

這是正確的方法是什麼?錯誤在哪裏?

回答

0

我試過這個,但它一直返回整個對象。

該方法返回與給定規範匹配的單個實體。請檢查here

根據我的理解,這是正確的方法。 U可以像往常一樣訪問實體的屬性(例如MyInfo.getIdProperty())