选择特定列的 Spring Data JPA 规范
我们可以通过在我们的存储库接口中编写自定义@Query 方法来选择特定的列.但是,我不想为不同的属性写这么多方法.
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();
}
};
}
}
用作:
MyInfo findOne(Specification(properties,idValue, idProperty));
这是正确的方法吗?哪里错了?
Is this the correct way? Where is the mistake?
推荐答案
目前的spring data jpa规范执行器仅限于where子句中的条件,所以你不能改变选中的列,它隐含地仅限于完整实体(查看 JpaSpecificationExecutor
接口文档).您必须使用自定义存储库实现,或者转移到命名查询-
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-
春天数据 JPA 和 Querydsl 使用 bean/构造函数投影获取列子集
相关文章