我们可以通过在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));
这是正确的方法吗?错误在哪里?