我们可以通过在 Repository Interface 中编写自定义 @Query 方法来选择特定的列。但是,我不想为不同的属性编写那么多方法。
我试过了,但它一直返回整个对象。
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));
这是正确的方法吗?哪里错了?
最佳答案
当前的 spring 数据 jpa 规范执行器仅限于 where 子句中的条件,因此您不能更改选定的列,它隐含地仅限于完整实体(看看 JpaSpecificationExecutor
接口(interface)文档)。您将不得不使用自定义存储库实现,或移动到命名查询-
Spring Data JPA and Querydsl to fetch subset of columns using bean/constructor projection
关于java - 用于选择特定列的 Spring Data JPA 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22171822/