javaspringspring-data-commons

OrderBy results in error with older Spring Data


I wanted to write a method that returns a paged and sorted list of entities, and I was hoping that Spring Data can derive the query from the method name directly. The following repository definition from a shared module works well when used in one module and fails with "Context initialization failed" error when used in another.

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

The first module is newer and it depends on Spring Data JPA 1.11.0 + Spring Data Commons 1.13.0. The second module is older and it depends on Spring Data JPA 1.6.2 + Spring Data Commons 1.8.2.

Here's a piece of logs:

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

How to rewrite this method so it works in all versions of Spring Data without errors?


Solution

  • No need to rewrite anything, just specify an explicit sort order (Asc or Desc):

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

    You encountered this error because of DATACMNS-641 (fixed in Spring Data Commons 1.10).