我們可以通過在我們的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));
這是正確的方法是什麼?錯誤在哪裏?