【问题标题】:Spring Data - PagingAndSortingRepository with custom query (HQL)?Spring Data - 带有自定义查询(HQL)的 PagingAndSortingRepository?
【发布时间】:2019-03-13 06:09:13
【问题描述】:

尝试将 PagingAndSortingRepository 与自定义查询混合使用,但没有成功..

自定义仓库:

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

实施回购:

@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;
       }
   }
}

注入服务的repo:

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

如果我只是扩展 CrudRepository(没有 Pageable 方法),那么一切都很好。尝试扩展 PagingAndSortingRepository(使用或不使用 Pageable 方法)然后 Spring 无法启动

PropertyReferenceException: No property getActiveSites found for type SitesDbRecord!

将 PagingAndSortingRepository 与自定义查询一起使用的正确方法是什么?可能弄错了,但我认为提供分页/排序处理是 Spring 的责任。

【问题讨论】:

  • 你试过@Query注解吗?
  • 用 Spring 做我的第一步,不熟悉这个.. 应该有帮助吗?
  • 因为getActiveSites( Pageable pageable ) 没有实现。只需删除此方法或将其移至SiteRepositoryCustom 并在SiteRepositoryImpl 中实现即可。

标签: spring-boot spring-data-jpa spring-data


【解决方案1】:

如果SitesDbRecord 有名为active 的布尔属性,它应该是:

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

无需扩展您的自定义存储库,只需实现 PagingAndSortingRepository

【讨论】:

  • 我必须遵循这个命名约定吗?如果遵循这个约定,那么不需要为这两种方法提供实现吗?
  • 如果您愿意,可以,第二个问题可以。这是实现存储库层的快速方法。
  • 如果我们需要自定义代码,比如过滤 10 多个字段并支持 Pageable 怎么办?
猜你喜欢
  • 2019-10-31
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 2015-03-25
  • 2015-12-07
相关资源
最近更新 更多