java - 用于选择特定列的 Spring Data JPA 规范

标签 java spring jpa spring-data spring-data-jpa

我们可以通过在 Repository Interface 中编写自定义 @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));

这是正确的方法吗?哪里错了?

最佳答案

当前的 spring 数据 jpa 规范执行器仅限于 where 子句中的条件,因此您不能更改选定的列,它隐含地仅限于完整实体(看看 JpaSpecificationExecutor接口(interface)文档)。您将不得不使用自定义存储库实现,或移动到命名查询-

Spring Data JPA and Querydsl to fetch subset of columns using bean/constructor projection

关于java - 用于选择特定列的 Spring Data JPA 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22171822/

相关文章:

java - 如何在 Spring Boot 中实现 Oracle AQ 队列?

java - JPA - JSF - 重新渲染 - Ajax 为什么我必须重新启动服务器才能看到添加了新项目?

java - 如何在spring boot中使用应用程序上下文获取bean

java - 带有 OneToMany 的 Spring Data Projection 返回太多结果

java - 使用 JPA 将值添加到数据库时出现问题

java - 为什么 Json 无法为 java 枚举正确生成?

java - 为什么在将项目添加到 HashMap 之前 hashCode() 返回零?

web-services - 如何指定 webServiceTemplate 使用哪种版本的 soap?

java - Spring JUnit4 手动/自动布线困境

PostgreSQL、枚举、JPA、EclipseLink