Spring Data - 为什么不能使用本机查询进行分页 [英] Spring Data - Why it's not possible to have paging with native query

查看:17
本文介绍了Spring Data - 为什么不能使用本机查询进行分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个名为 MyEntity 的实体.可以使用 @Query 和命名查询来查询可分页结果,例如

Let's say we have an entity called MyEntity. It is possible to query pageable results using @Query and with named queries, e.g.

 @Query(value = "select e from MyEntity e where e.enabled = true")
 Page<MyEntity> findAllEnabled(Pageable pageable);

然而,本机查询无法实现相同的效果,所以这个

However, it is not possible to achieve the same with native query, so this

 @Query(value = "select * from my_entity where enabled = true", nativeQuery = true)
 Page<MyEntity> findAllEnabled(Pageable pageable);

行不通.

这背后的原因是什么?是否可以使 Pageable 与本机查询一起使用?

What are the reasons behind this? Is it possible to make Pageable working with native queries?

推荐答案

这是描述,在 spring data jpa 文档中给出 (http://docs.spring.io/spring-data/jpa/docs/1.8.0.M1/reference/html/)

This is description, given in spring data jpa documentation (http://docs.spring.io/spring-data/jpa/docs/1.8.0.M1/reference/html/)

原生查询@Query注解允许执行原生查询通过将 nativeQuery 标志设置为 true.请注意,我们目前没有支持对原生查询执行分页或动态排序因为我们必须操作声明的实际查询而我们不能这样做这对于原生 SQL 来说是可靠的.

Native queriesThe @Query annotation allows to execute native queries by setting the nativeQuery flag to true. Note, that we currently don’t support execution of pagination or dynamic sorting for native queries as we’d have to manipulate the actual query declared and we cannot do this reliably for native SQL.

JPQL 抽象了 SQL 实现及其提供者的细节,并使 ORM 框架负责生成正确的 SQL.

JPQL abstracts SQL implementation and it's providers specifics, and makes it responsibility of ORM framework to generate correct SQL.

  1. 因此,通过使用 JPQL 形式的 Pagination,Spring 只需要生成正确的 JPQL,并将在 ORM 级别对其进行解释以纠正 SQL.

  1. So by using Pagination in JPQL form, Spring just needs to generate correct JPQL, and it will be interpreted on ORM level to correct SQL.

当使用 SQL 这样做时,意味着 Spring 知道如何为绝大多数 RDBMS 生成正确的 SQL,重复 ORM 功能,这会带来太多开销.

While doing so with SQL, would imply that Spring knows how to generated correct SQL for the vast majorities of RDBMS, duplicating ORM functionality, which is too much overhead.

这篇关于Spring Data - 为什么不能使用本机查询进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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