Spring Data Rest和count查询

3

我正在使用Spring Data Rest进行几行代码的实验。我无法找到任何通过REST发送一个简单请求来计算特定实体的所有记录数量的内容。

假设我有以下实体:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

这将需要访问以下代码库:

import java.util.List;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
}

有没有一种通过REST方式知道我数据库中有多少个“Person”实体被保存的方法,且没有指定条件?

PagingAndSortingRepository有一个返回Iterable的findAll()方法。也许这就是你要找的?或者是count()方法? - Danila Zharenkov
是的,但我该如何使用REST调用它,例如使用Postman? - Lorelorelore
3个回答

3

Spring Data REST 仅支持标准的HTTP方法,例如GET、POST、PUT、PATCH、DELETE等。

但如果你需要获取资源的总数,你可以比如说发送GET请求并检查其页面块:

  "page" : {
    "size" : 5,
    <b>"totalElements" : 50,</b>
    "totalPages" : 10,
    "number" : 1 
  }

或者创建自定义控制器更新 对于集合资源上的GET方法,SDR返回带有资源元素总数的可分页结果。SDR会触发两个查询:一个用于页面上的元素,另一个是所有元素的计数查询。

嗯...所以...totalElements字段显示查询中有多少条记录可用。我理解它向我展示了我已经接收到的当前页面上有多少条记录。我是对的吗? - Lorelorelore
@Lorelorelore 不是,它是“总元素”的数量。但是 size 是页面的大小。 - Cepr0
好的,现在清楚了。你帮了我很多,谢谢! - Lorelorelore

3
另一种选择是引入自定义查询方法。这些方法通过REST数据存储库公开。
例如,使用JPA:
@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
    @Query("select count(p) from Person p")
    Long findCount();
}

使用 MongoDB:

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends MongoRepository<Person, Long> {
    @Query(value = "{}", count = true)
    Long findCount();
}

然后在rest中进行调用,只需使用/people/search/findCount,它只返回主体中的数字,没有额外的属性,例如:
200 success

date: Wed, 09 May 2018 17:59:13 GMT
transfer-encoding: chunked
content-type: application/hal+json;charset=UTF-8

154

无需解析GET响应并不必要地获取记录。

-1

看起来CrudRepository的count()方法是你的候选。根据javadoc:

/**
 * Returns the number of entities available.
 * 
 * @return the number of entities
 */
long count();

是的,但我怎样才能使用REST调用它,例如用Postman? - Lorelorelore
1
这个方法没有被Spring Data REST公开。 - Brian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接