【问题标题】:How to write a findByCritera1InAndCritera2In using (spring data) CrudRepository with parameters being optional如何使用(弹簧数据)CrudRepository 编写 findByCritera1InAndCritera2In,参数可选
【发布时间】:2016-08-18 16:56:03
【问题描述】:

我正在使用带有 spring 数据的 spring boot,特别是扩展 CrudRepository 的类 PagingAndSortingRepository。
我需要一个查询,如果匹配四个列表中的任何一个,则返回表的所有条目,当它为空(或空)时忽略它。
如果我使用 findByTypeInAndLocaleInAndCategoryInAndTagIn 并且其中一个列表为空,则结果也为空。所以我最终写了几个查找器,并根据哪些列表是空的,使用不同的。
是否可以将其合并到一个查找器中?

例如如果我使用 findByTypeAndLocale,如果列表类型为空,我想匹配所有类型的值。

对任何提示都很满意。

@Repository
public interface FeedRepository extends PagingAndSortingRepository<FeedEntry, Long>, JpaSpecificationExecutor<FeedEntry> {
    public List<FeedEntry> findByGuid(String guid);
    public Page<FeedEntry> findAll(Pageable pageable);
    public Page<FeedEntry> findByLocale(List<LocaleEnum> type, Pageable pageable);
    public Page<FeedEntry> findByType(List<FeedTypeEnum> type, Pageable pageable);
    public Page<FeedEntry> findByTypeAndLocale(FeedTypeEnum type, LocaleEnum locale, Pageable pageable);    
    public Page<FeedEntry> findByTypeInAndLocaleIn(List<FeedTypeEnum> type,List<LocaleEnum> locale, Pageable pageable);
    public Page<FeedEntry> findByTypeInAndLocaleInAndCategoryIn(List<FeedTypeEnum> type,List<LocaleEnum> locale, List<String> category, Pageable pageable);
    public Page<FeedEntry> findByTypeInAndLocaleInAndTagIn(List<FeedTypeEnum> type,List<LocaleEnum> locale, List<String> tag, Pageable pageable);
    public Page<FeedEntry> findByTypeInAndLocaleInAndCategoryInAndTagIn(List<FeedTypeEnum> type,List<LocaleEnum> locale, List<String> category, List<String> tag, Pageable pageable);      
} 

【问题讨论】:

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


    【解决方案1】:

    你不能像现在这样去做。如果列表为空,则表示没有任何值与您的条件查询匹配。

    要执行您要查找的内容,您需要使用与CrudRepository 兼容的QBE (Query By example) 来执行此操作

    为什么?您需要一个动态查询,正如文档所说:

    Query by Example (QBE) 是一种用户友好的查询技术,具有 简单的界面。它允许创建动态查询,并且不允许 需要编写包含字段名称的查询。实际上,查询方式 示例不需要使用特定于商店的查询来编写查询 语言。

    文档示例:

    public interface PersonRepository extends JpaRepository<Person, String> { … }
    
    public class PersonService {
    
      @Autowired PersonRepository personRepository;
    
      public List<Person> findPeople(Person probe) {
        return personRepository.findAll(Example.of(probe));
      }
    

    }

    **为你的案例做例子...

    【讨论】:

      【解决方案2】:

      恐怕目前不可能。

      恕我直言,实现目标的最佳方法是使用 Spring Data JPA 规范 (http://docs.spring.io/spring-data/jpa/docs/1.10.2.RELEASE/reference/html/#specifications) 并手动检查每个参数的非空值...

      【讨论】:

        猜你喜欢
        • 2019-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-03
        • 1970-01-01
        • 1970-01-01
        • 2018-12-10
        • 1970-01-01
        相关资源
        最近更新 更多