Seffy
Seffy

Reputation: 1085

Spring Data - PagingAndSortingRepository with custom query (HQL)?

Trying to mix PagingAndSortingRepository with custom queries, no luck..

Custom repo:

public interface SiteRepositoryCustom
{
    public List<SitesDbRecord> getActiveSites();
}

Impl repo:

@Repository
public class SiteRepositoryImpl implements SiteRepositoryCustom
{
    private static final Logger logger = ...

    @PersistenceContext
    private EntityManager em;

    @Override
    public List<SitesDbRecord> getActiveSites()
    {
        logger.info( "getActiveSites start" );

       try
       {
          String hql = "select s from SitesDbRecord s where s.isActive = true";

          return em.createQuery( hql ).setMaxResults( Integer.MAX_VALUE ).getResultList();
       }
       catch ( Exception e )
       {
          logger.error( "getActiveSites failed.", e );

          return null;
       }
   }
}

The repo injected to the service:

public interface SiteRepository extends PagingAndSortingRepository<SitesDbRecord, Integer>, SiteRepositoryCustom  {
    public List<SitesDbRecord> getActiveSites( Pageable pageable );
    public List<SitesDbRecord> getActiveSites();
}

If I just extend CrudRepository (without the Pageable method) then all is OK. Trying to extend PagingAndSortingRepository (with or without the Pageable method) then Spring fails to boot with

PropertyReferenceException: No property getActiveSites found for type SitesDbRecord!

What is the correct way to use PagingAndSortingRepository with custom queries? Probably got it wrong, but I assumed it's Spring responsibility to provide the handling of paging/sorting.

Upvotes: 1

Views: 2138

Answers (1)

ValerioMC
ValerioMC

Reputation: 3186

If SitesDbRecord has boolean property named active it should be:

public interface SiteRepository extends PagingAndSortingRepository<SitesDbRecord, Integer> {
    public List<SitesDbRecord> findByActiveIsTrue( Pageable pageable );
    public List<SitesDbRecord> findByActiveIsTrue();
}

There is no need to extend your Custom repository, just implement PagingAndSortingRepository

Upvotes: 1

Related Questions