【问题标题】:IllegalStateException: Operator IN on type requires a Collection argumentIllegalStateException:类型上的运算符 IN 需要 Collection 参数
【发布时间】:2020-10-19 20:11:08
【问题描述】:

我想创建这个 Spring Data Repository:

存储库:

@Repository
public interface CustomersRepository extends JpaRepository<Users, Integer>, JpaSpecificationExecutor<Users> {

    Page<Users> findAllByTypeIn(Pageable page, String... types);

    Page<Users> findAllByTypeIn(Specification<Users> specification, Pageable pageable, List<String> types);
}

服务:

@Override
public Page<Users> findAll(int page, int size) {
    return dao.findAllByTypeIn(PageRequest.of(page, size), "CustomerUser");
}

@Override
public Page<Users> getAllBySpecification(Specification<Users> specification, Pageable pageable) {
    return this.dao.findAllByTypeIn(specification, pageable, List.of("CustomerUser"));
}

当我部署包时,我得到了这个错误:

Caused by: java.lang.IllegalStateException: Operator IN on type requires a Collection argument, found interface org.springframework.data.jpa.domain.Specification in method public abstract org.springframework.data.domain.Page org.engine.plugin.production.service.CustomersRepository.findAllByTypeIn(org.springframework.data.jpa.domain.Specification,org.springframework.data.domain.Pageable,java.util.List).

你知道如何解决这个问题吗?

【问题讨论】:

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


    【解决方案1】:

    您不能以这种方式将 Specification 与 Spring 数据驱动查询一起使用。你应该使用JpaSpecificationExecutor

    FindByTypeIn 和类似定义派生查询的方法,这意味着 Spring Data JPA 从您的方法名称派生要执行的查询,此功能提供给您的 CustomerRepository,因为您从 JpaRepository 扩展了您的存储库,另一方面,findAll(Specification specification, Pagable pagable) 来自另一个接口 JpaSpecificationExecutor,可以扩展这两个接口,但这并不意味着您可以将它们的功能混合和匹配在一起:

    所以你应该像下面这样定义你的存储库,你应该省略在参数中包含 Specification 的方法,因为它们来自 JpaSpecificationExecutor

    @Repository
    public interface CustomerRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {
            
            Collection<User> findByTypeIn(Collection<String> types, Pageable pageable);
    //      omit methods which have Specification here they are already defined in JpaSpecificationExecutor interface 
    }
    

    您的情况没有问题,因为您可以在 Specification 中包含您的 In 运算符我不会详细说明如何做到这一点,因为对于这种特定情况已经有一个很好的答案:

    Add WHERE IN clause to JPA Specification

    该链接可以解决您的问题,但是如果您想了解更多关于 JpaSpecificationExecutor 的信息,您可以阅读以下链接了解更多详情:

    spring data jpa specification

    【讨论】:

    • 你能再告诉我需要更改哪些行吗?
    • 我已经详细说明了这一点,希望对您有所帮助。
    猜你喜欢
    • 2015-03-27
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 2013-06-13
    • 2015-01-30
    • 2020-06-09
    • 2014-06-23
    • 2015-10-23
    相关资源
    最近更新 更多