You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义Slice返回类型的findAll方法与PagingAndSortingRepository冲突报错

问题原因与解决方案

错误原因

你定义的findAll(Pageable pageable)方法返回Slice<Book>,但JpaRepository继承的PagingAndSortingRepository接口中,同名方法的返回类型是Page<T>。Java方法重写要求返回类型必须是协变类型(即子类方法的返回类型需是父类方法返回类型的子类),而Slice是Page的父类,不符合协变规则,因此触发返回类型不兼容的报错。

解决方法

方案1:自定义方法名(推荐)

避免重写父接口的方法,改用自定义方法名来返回Slice:

import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

@SuppressWarnings("unused")
@Repository
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {
    // 自定义方法名,避免与父接口方法冲突
    Slice<Book> findAllAsSlice(Pageable pageable);
}

方案2:使用@Query标注强制自定义查询

如果需要保留findAll方法名,可以通过@Query标注明确这是自定义查询,而非重写父接口方法:

import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@SuppressWarnings("unused")
@Repository
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {
    @Query("select b from Book b")
    Slice<Book> findAll(Pageable pageable);
}

两种方案都能让Spring Data JPA正确识别并返回Slice类型结果,方案1更清晰,能避免方法名冲突带来的混淆。

内容的提问来源于stack exchange,提问作者MIM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 19:22:04