问题描述
我们可以通过在存储库接口中编写自定义@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/构造函数投影来获取列的子集
这篇关于Spring Data JPA规范以选择特定的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!