Spring Data JPA Specification to Select Specific Columns(选择特定列的 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/构造函数投影获取列子集
这篇关于选择特定列的 Spring Data JPA 规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:选择特定列的 Spring Data JPA 规范
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
