如何正确过滤 Spring REST 数据

huangapple go评论76阅读模式
英文:

How to properly filter Spring REST data

问题

我有一个使用Spring Data REST创建的服务,其中包含一个单一的@Entity和Repository。当我运行以下命令:

$ curl localhost:8080/api

我会得到存储在我的Repository中的所有数据,并且它按预期工作。我还有一个小的React前端,在那里显示了那些数据。

我的问题是:我应该在哪里对数据进行筛选?例如,也许我想要所有id > 10的条目。我是在前端中筛选响应还是应该以某种方式进行REST调用,以仅返回所需的条目?

如果应该采用后者,那么该如何操作呢?

谢谢。

英文:

I have a Spring Data REST service with a single @Entity and Repository. When I run

$ curl localhost:8080/api

I get all the data stored in my repository and it works as expected. I also have a small React front end and I display that data there.

My question is: Where should I filter the data? For example maybe I want all the entries with id > 10. Should I just filter the response in my front end or should I make the REST call in such a way that it returns just the required entries?

If I should do the latter, then how?

Thanks.

答案1

得分: 3

在后端或更具体地说,通过数据库查询进行筛选。

数据库已经针对这些操作进行了优化。因此,您可以减少从后端传输到前端的数据量,减轻前端的负担,因为只有用户请求的数据会被前端处理。

另一个好处是,如果您有多个前端(例如网站和移动应用程序),您只需要在后端实现一次筛选功能,而不是在每个客户端中都实现两次。

英文:

Filter in the backend or - more specifically - with the database query.

The database is optimized for those operations. Thus, you can reduce the data transmitted from the backend to the frontend and reduce the load on the frontend since only data that is requested by the user will be processed by the frontend.

Another benefit is that if you have multiple frontends (e.g. website & mobile app), you have to implement filter functionality only once (in the backend) instead of twice (in each client)

答案2

得分: 2

如果始终如此,为什么要让“前端”在所有时间内都对结果进行过滤,增加额外负担呢?

实现一个新的方法,该方法将返回所需结果(例如,id > 10),并使用@Query进行注释,在其中提供JPQL或者native query

@Query("SELECT c FROM Customer c WHERE c.id > 10")
Collection<Customer> findAllActiveCustomers();

然而,如果选择使用本地查询,不要忘记在@Query内部加入nativeQuery = true

英文:

If it is always the case, why would you put extra burden on front-end shoulders to filter the results all the time?

Implement a new method which returns the desired results(e.g id > 10) and annotate it with @Query and provide JPQL or native query inside it

@Query(&quot;SELECT c FROM Customer c WHERE c.id &gt; 10&quot;)
Collection&lt;Customer&gt; findAllActiveCustomers();

However, if you choose native query do not forget to put nativeQuery = true inside @Query

huangapple
  • 本文由 发表于 2020年7月26日 08:12:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63094843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定