2014-03-12 125 views
34

我使用Spring数据JPA,当我使用@Query来定义查询WITHOUTPageable,它的工作原理:弹簧数据的JPA @query和分页

public interface UrnMappingRepository extends JpaRepository<UrnMapping, Long> { 
    @Query(value = "select * from internal_uddi where urn like %?1% or contact like %?1%", 
      nativeQuery = true) 
    List<UrnMapping> fullTextSearch(String text); 
} 

但是,如果我添加第二参数Pageable,@Query将不起作用,Spring将解析该方法的名称,然后抛出例外No property full found。这是一个错误?

public interface UrnMappingRepository extends JpaRepository<UrnMapping, Long> { 
    @Query(value = "select * from internal_uddi where urn like %?1% or contact like %?1%", 
      nativeQuery = true) 
    Page<UrnMapping> fullTextSearch(String text, Pageable pageable); 
} 

回答

23

类似的问题是asked on the Spring forums,它指出,申请分页,第二子查询必须的。由于子查询引用的是相同的字段,因此您需要确保查询对引用的实体/表使用别名。这意味着,如果你写:

select * from internal_uddi where urn like 

而应该有:

select * from internal_uddi iu where iu.urn like ... 
+0

不幸的是,这不适用于本机查询。你知道是否有可能实现本机查询? – vtor

+5

如果你想写本地查询,那么你显然需要编写查询来自己做分页。 – Steve

3

考虑到UrnMapping类映射到internal_uddi表,我建议这样的:

@Repository 
public interface UrnMappingRepository extends JpaRepository<UrnMapping, Long> { 

    @Query(value = "select iu from UrnMapping iu where iu.urn like %:text% or iu.contact like %:text%") 
    Page<UrnMapping> fullTextSearch(@Param("text") String text, Pageable pageable); 
} 

请注意,您可能必须使用动态请求关闭本机查询。

13

您可以使用本机查询分页。这是记录在这里:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query

但是,您可以通过指定计数查询自己使用分页机查询: 例51.申报分页本地计数查询的查询方法使用@Query

public interface UserRepository extends JpaRepository<User, Long> { 

    @Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1", 
    countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1", 
    nativeQuery = true) 
    Page<User> findByLastname(String lastname, Pageable pageable); 
}