【问题标题】:Pageable and @Param in a spring data JpaRepository method issue [2]Spring 数据 JpaRepository 方法问题中的 Pageable 和 @Param [2]
【发布时间】:2014-11-16 11:35:19
【问题描述】:

我知道this 的问题,但使用org.springframework.data:spring-data-jpa:1.7.0.RELEASE 我仍然遇到同样的问题(Either use @Param on all parameters except Pageable and Sort typed once, or none at all!)。我的课是:

public interface BalanceHistoryRepository extends JpaRepository<BalanceHistory, Long> {
    @Query("select bh from BalanceHistory bh where bh.account.id = :idAccount")
    public BalanceHistory findCurrentBalanceByAccountNumber(PageRequest pageCriteira, @Param("idAccount") long idAccount);
}

编辑

呼叫:

 Pageable page = new PageRequest(0, 1, Sort.Direction.DESC, "date");
        BalanceHistory bh = balanceHistoryRepository.findCurrentBalanceByAccountNumber(1,page);

方法:

@Query("select bh from BalanceHistory bh where bh.account.id = :idAccount")
public BalanceHistory findCurrentBalanceByAccountNumber(@Param("idAccount") long idAccount, Pageable pageCriteira);

【问题讨论】:

  • 如果您依赖于旧版本的 spring-data-commons 升级 spring-data-jpa 将无济于事,则该错误在 spring-data-commons 中。
  • 那些 java.lang 的家伙需要冷静下来......

标签: java spring spring-mvc jpa spring-data


【解决方案1】:

确保使用Pageable 而不是PageRequest,以便将第一个参数识别为不绑定到实际查询的参数。此外,您需要将返回类型更改为 PageList,因为您将返回多个结果。

public interface BalanceHistoryRepository extends CrudRepository<BalanceHistory, Long> {

  @Query("select bh from BalanceHistory bh where bh.account.id = :idAccount")
  Page<BalanceHistory> findCurrentBalanceByAccountNumber(@Param("idAccount") long idAccount, Pageable pageable);
}

这应该可以解决问题。请注意,我们通常不建议扩展商店特定的接口,因为它们公开了商店特定的 API,只有在真正需要时才应该公开。

【讨论】:

  • 感谢您的意见!此更改会产生 java.lang.IllegalStateException: Method has to have one of the following return types! [interface org.springframework.data.domain.Slice, interface org.springframework.data.domain.Page, interface java.util.List] 异常。请查看我的编辑:)
  • 修正您的退货类型。您输入了Pageable,因此结果必须是一页结果,而不是单个结果。
  • @Oliver:为什么参数必须是Pageable,我将参数设为PageRequest,它会抛出问题中提到的这个异常。
  • 因为你指的是接口,而不是实现。
【解决方案2】:

我在不小心导入了错误的Pageable 类时遇到了同样的异常。

如果您在存储库中也使用PageRequest,也会发生这种情况。

应该是,

import org.springframework.data.domain.Pageable;

【讨论】:

    猜你喜欢
    • 2014-08-01
    • 2016-05-26
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 2020-08-22
    • 2019-03-08
    相关资源
    最近更新 更多