简体   繁体   中英

Spring Pageable doesn't work for ordering

On the internet I found that Spring can do pagination as well as ordering for a list of data retrieved from the database. Accordingly, I created my test class as following:

 @Test
 public void testPageable() {
      int pageSize = 5;
      Sort sort = new Sort( Direction.DESC, "someColumnA" );
      Pageable pageable = new PageRequest( 0, pageSize, sort );
      List<SomeObject> listOFSomeObject = getDao().getListData( "paramOne", pageable );
 }

When I analyze the List I never get ordering of someColumnA in a DESC fashion, although I get back only 5 records which is correct.

Can someone please let me know what I might be doing wrong? Just as an FYI, I am using Hibernate for database access and Spring named query.

EDIT: Code for getListData()->

public interface SomeRepository
                extends JpaRepository<EntityMappedViaHibernate, String> {

    List<Object[]> getListData( @Param(value = PARAM_ONE) final String paramOne, Pageable pageable );
}

My Hibernate entity is as follows:

@NamedQueries(value = {
@NamedQuery(name = "SomeRepository.getListData", query = "select id, someColumnA from EntityMappedViaHibernate where id = :paramOne")
})
@Entity
@Table(name = "entity_mapped_via_hibernate")
public class EntityMappedViaHibernate implements Serializable {
  // Code Omitted on purpose
}

So those of you who are struggling like me the solution to this problem is that you need to have the query inside the Repository. In my case it has to be inside the SomeRepository. So in the code of the repo do the following:

public interface SomeRepository
            extends JpaRepository<EntityMappedViaHibernate, String> {

@Query("select id, someColumnA from EntityMappedViaHibernate where id = :paramOne")
List<Object[]> getListData( @Param(value = PARAM_ONE) final String paramOne, Pageable pageable );
}

No need to have the NamedQuery inside the EntityMappedViaHibernate. That's it!!

Hope someone find the answer and do not struggle like I did.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM