如何在Spring Data JPA中将投影接口与分页一起使用? [英] How to use projection interfaces with pagination in Spring Data JPA?
问题描述
I'm trying to get a page of a partial entity (NetworkSimple) using the new feature of spring data, projections
我已经检查了文档,并且如果我仅要求:
I've checked the documentation and if I request only:
Collection<NetworkSimple> findAllProjectedBy();
它可以工作,但是如果我使用的是可分页:
It works, but if I'm using pageable:
Page<NetworkSimple> findAllProjectedBy(Pageable pageable);
它抛出一个错误:
org.hibernate.jpa.criteria.expression.function.AggregationFunction$COUNT cannot be cast to org.hibernate.jpa.criteria.expression.CompoundSelectionImpl
任何人都已经为此工作了吗?
Any one has already work with this ?
我的NetworkSimple类如下:
My NetworkSimple class is the following:
public interface NetworkSimple {
Long getId();
String getNetworkName();
Boolean getIsActive();
}
推荐答案
Note: This feature should work in the way described by the original poster but due to this bug it didn't. The bug has been fixed for the Hopper SR2 release, if you're stuck on an earlier version then the workaround below will work.
可以将Pageable
与Spring Data JPA 1.10(Hopper)中引入的新查询投影功能一起使用.您将需要使用@Query
批注并为所需字段手动编写查询,还必须使用AS
为它们加上别名,以使Spring Data能够弄清楚如何对结果进行投影.在
It is possible to use Pageable
with the new query projection features introduced in Spring Data JPA 1.10 (Hopper). You will need to use the @Query
annotation and manually write a query for the fields you require, they must also be aliased using AS
to allow Spring Data to figure out how to project the results. There is a good example in spring-boot-samples part of the spring boot repository.
在您的示例中,这将非常简单:
In your example it would be quite simple:
@Query("SELECT n.id AS id, n.name AS networkName, n.active AS isActive FROM Network n")
Page<NetworkSimple> findAllProjectedBy(Pageable pageable);
我已经假设您的实体看起来像这样:
I have made the assumption that your entity looks something like this:
@Entity
public class Network
{
@Id
@GeneratedValue
private Long id;
@Column
private String name;
@Column
private boolean active;
...
}
Spring Data将自动派生一个用于查询分页信息的计数查询.还可以利用查询中的联接来获取关联,然后在投影中对其进行汇总.
Spring Data will derive a count query automatically for the paging information. It is also possible to make use of joins in the query to fetch associations and then summarise them in the projection.
这篇关于如何在Spring Data JPA中将投影接口与分页一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!