【问题标题】:Spring data jpa repository find by multi elementsSpring数据jpa存储库通过多元素查找
【发布时间】:2017-08-04 14:41:42
【问题描述】:

我在我的项目中使用Spring Data JPA。所以在存储库中,我通过以下方式定义了一个列表:

List<Branch> findByNameContainingAndByTypeContaining(String name, String type)

它在这种情况下有效,但是,在搜索表单中,我得到了 10 多个搜索条件,这意味着在搜索方法中,它需要 10 多个元素,并且正确地,它们的字段具有值。

例如:

name: abc
type: primary
enabled: true
createdBy: null
modifiedBy: null
and so more

对于findBy 方法,如果我发送空白,它可以工作,但值为空。而且,要搜索的领域太多了。所以我正在寻找一种更好的方法来搜索这样的表格。在 Grails 框架中,我可以为此创建 nameQueries,但在 Spring JPA 中找不到更好的方法。

有什么想法吗?谢谢。

【问题讨论】:

    标签: java spring hibernate spring-mvc spring-data-jpa


    【解决方案1】:

    您可以使用QueryByExample API,例如:

    Branch branch = new Branch();                          
    branch.setName("Foo");
    branch.setEnabled(true)                           
    
    ExampleMatcher matcher = ExampleMatcher.matching();        
    Example<Branch> example = Example.of(branch, matcher);
    branchRepository.findAll(example)
    

    您可以选择包含或忽略null 值,并指定区分大小写等。

    更多例子是here in the Spring Data Docs

    【讨论】:

    • 很高兴我能帮上忙 :)
    • 嗨,有个问题,现在,我有一个搜索表单,有 fromDate 和 toDate,它需要与 Branch 中的 datetime 字段进行比较才能获取数据,我该怎么做?谢谢。
    • @TranTam 无法使用 QueryByExample:stackoverflow.com/a/41056515/1258079
    猜你喜欢
    • 2017-05-26
    • 2016-07-28
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2019-12-22
    相关资源
    最近更新 更多