OrderBy 导致旧的 Spring 数据出错

OrderBy results in error with older Spring Data

我想编写一个方法,returns 实体的分页和排序列表,我希望 Spring Data 可以直接从方法名称派生查询。共享模块中的以下存储库定义在一个模块中使用时运行良好,在另一个模块中使用时失败并出现 "Context initialization failed" 错误。

@Repository
public interface AppleDao extends JpaRepository<Apple, Long> {
    Page<Apple> getAllByVarietyEqualsOrderById(Variety variety, Pageable pageable);
}

第一个模块较新,它依赖于 Spring Data JPA 1.11.0 + Spring Data Commons 1.13.0。第二个模块较旧,它依赖于 Spring Data JPA 1.6.2 + Spring Data Commons 1.8.2.

这是一段日志:

SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'appleServiceImpl': Injection of autowired dependencies failed;
    nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private by.naxa.dao.apple.AppleDao by.naxa.services.apple.AppleServiceImpl.appleDao;
    nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'appleDao': Invocation of init method failed;
    nested exception is java.lang.IllegalArgumentException: Could not create query metamodel for method public abstract org.springframework.data.domain.Page by.naxa.dao.apple.AppleDao.getAllByVarietyEqualsOrderById(by.naxa.entity.apple.Variety,org.springframework.data.domain.Pageable)!
    Invalid order syntax for part Id

如何重写此方法使其适用于所有版本的 Spring 数据而不会出错?

无需重写任何内容,只需指定明确的排序顺序(AscDesc):

@Repository
public interface AppleDao extends JpaRepository<Apple, Long> {
    Page<Apple> getAllByVarietyEqualsOrderByIdAsc(Variety variety, Pageable pageable);
}

您遇到此错误是因为 DATACMNS-641(已在 Spring 数据共享 1.10).