【问题标题】:Incompatible types List and Page不兼容的类型列表和页面
【发布时间】:2016-05-14 16:13:01
【问题描述】:

我正在使用 JHipster 开发一个 web 应用程序来管理付款,并希望过滤用户可以看到的付款,以便他只能看到他的付款。为此,我在 Youtube 上关注了 Matt Raible 的 blog tutorial。他使用由 JHipster 生成的 findByUserIsCurrentUser()。

List<Blog> blogs = blogRepository.findByUserIsCurrentUser();

当我在我的项目中进行相同的更改时,我发现我必须返回的类型是一个 Page 并且我得到一个不兼容的类型错误,这是我的方法:

public Page<Payment> findAll(Pageable pageable) {
    log.debug("Request to get all Payments");
    Page<Payment> result = paymentRepository.findByUserIsCurrentUser();
    return result;
}

如果我更改在 PaymentRepository 中声明的 findByUserIsCurrentUser() 的 findAll(pageable),如下所示

public interface PaymentRepository extends JpaRepository<Payment,Long> {
    @Query("select payment from Payment payment where payment.user.login = ?#{principal.username}")
    List<Payment> findByUserIsCurrentUser();
}

我收到以下错误:

我该如何解决这个问题?

【问题讨论】:

    标签: spring-boot jhipster


    【解决方案1】:

    您可以通过两种方式解决此问题。这是假设您正在使用一项服务,如果不是,它仍然非常相似:

    方法 1:如果您希望您的服务为当前用户返回所有付款,那么您需要修改您的服务,并且可能需要修改您的资源来处理列表而不是页面:

    public List<Payment> findAll() {
        log.debug("Request to get all Payments");
        List<Payment> result = paymentRepository.findByUserIsCurrentUser();
        return result;
    }
    

    在您的资源中:

    public List<Payment> getAllPayments() {
        log.debug("REST request to get all Payments");
        List<Payment> payments = paymentService.findAll();
        return payments;
    }
    

    或者,您可以将.jhipster/Payment.json 中的"pagination": "pagination" 更改为"pagination": "no" 并重新运行生成器。这将在没有分页的情况下重新生成服务、资源和存储库。

    方法2:如果你想让你的服务分页,你需要改变你的repository方法接受Pageable对象,并返回一个页面:

    public interface PaymentRepository extends JpaRepository<Payment,Long> {
        @Query("select payment from Payment payment where payment.user.login = ?#{principal.username}")
        Page<Payment> findByUserIsCurrentUser(Pageable pageable);
    }
    

    然后你需要从你的服务中传入可分页对象:

    public Page<Payment> findAll(Pageable pageable) {
        log.debug("Request to get all Payments");
        Page<Payment> result = paymentRepository.findByUserIsCurrentUser(pageable);
        return result;
    }
    

    这将根据pageable 对象包含的任何内容返回结果子集。这包括大小、页码、偏移量和排序。例如,大小为 20 且页码为 0 将返回前 20 个结果。将页码更改为 1 将返回接下来的 20 个结果。这些参数通常是从前端传递到您的 API 的——您会注意到 PaymentResource 中的 getAllPayments() 有一个 Pageable 参数。

    【讨论】:

    • 完美运行,非常感谢您的详细帮助!我使用了分页解决方案。
    猜你喜欢
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2013-04-19
    相关资源
    最近更新 更多