我们可以通过在Repository接口中编写自定义的@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));
这是正确的方式吗?错误在哪里?
发布于 2015-07-21 23:37:33
当前的spring data jpa规范执行器仅限于where子句中的条件,因此不能更改所选列,它隐含地仅限于完整实体(请查看JpaSpecificationExecutor
接口文档)。您将不得不使用自定义存储库实现,或者移动到命名查询-
Spring Data JPA and Querydsl to fetch subset of columns using bean/constructor projection
发布于 2014-03-06 17:45:54
我试过了,但它总是返回整个对象。
此方法返回与给定规范匹配的单个实体。请查看here
根据我的理解,这是正确的方式。您可以正常访问实体的属性(例如,MyInfo.getIdProperty()
发布于 2019-11-07 06:38:21
规范是where子句的抽象。由于JPA标准API的设计,您可以在规范中使用所有类型的东西,但是除了声明where子句之外,任何副作用的行为都是未定义的。
如果您想要控制选择列表,您可以使用带有投影的查询派生和非常有限的查询支持,或者在自定义方法中构造完整的自定义查询。
https://stackoverflow.com/questions/22171822
复制相似问题