选择特定列的 Spring Data JPA 规范 [英] Spring Data JPA Specification to Select Specific Columns

查看:19
本文介绍了选择特定列的 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 规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆