【发布时间】:2020-03-03 01:55:00
【问题描述】:
我们可以通过在我们的存储库接口中编写自定义@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));
这是正确的方法吗?哪里错了?
【问题讨论】:
-
您考虑过使用投影吗? baeldung.com/spring-data-jpa-projections
标签: java spring jpa spring-data spring-data-jpa