【问题标题】:Spring JPA repoistory findBy IN List - allow nullSpring JPA 存储库 findBy IN List - 允许 null
【发布时间】:2015-05-08 00:28:01
【问题描述】:

简短说明

当数组列表输入为空时,如何使findBy<Field>InIN 一起工作。例如忽略它。你的 DAO 会是什么样子?

更长的描述。

假设您正在创建一个搜索用户页面。

在应用程序中。您有多种过滤选项。

  • 已创建(始终给出日期范围)
  • 国家(null 时忽略并搜索所有国家)
  • 年龄范围
  • 职位名称
  • 等等……

现在假设您要在国家列表中搜索给定日期范围内的所有用户。

在搜索用户时,我总是会搜索加入的日期,但是如果我没有选择国家,我希望它搜索所有国家。

我计划添加除国家/地区以外的更多过滤选项。所以我真的不想为每个可能的字段组合创建很多 findBy 方法。

DAO

@Repository
public interface UserDao extends JpaRepository<User, Long> {

    public List<BeatRate> findByCreatedBetweenAndCountryIn(Date from, Date to, ArrayList<String> countryList );

}

测试

@Test
public void test() throws ParseException {

    Date from = new SimpleDateFormat( "yyyy-MM-dd" ).parse( "2015-01-01" );
    Date to   = new SimpleDateFormat("yyyy-MM-dd").parse("2015-05-15");

    //ArrayList<String> countryList = new ArrayList<String>();
    //countryList.add("UK");
    //countryList.add("Australia");
    //countryList.add("Japan");   // works ok when I have a list

    countryList = null;  // I want it to search for all countries when this is null -- this errors and doesnt work..  

    List<BeatRate> beatRates = beatRateDao.findByCreatedBetweenAndRentalCountryIn(from, to, countryList);

    Assert.assertTrue(beatRates.size()>0);

}

【问题讨论】:

    标签: spring hibernate jpa spring-data findby


    【解决方案1】:

    你可以有两种方法:

    beatRateDao.findByCreatedBetweenAndRentalCountryIn(from, to, countryList);
    

    beatRateDao.findByCreatedBetweenAndRental(from, to);
    

    然后根据countryList简单地选择一个:

    List<BeatRate> beatRates = (countryList != null && !countryList.isEmpty())
        ?  beatRateDao.findByCreatedBetweenAndRentalCountryIn(from, to, countryList)
        : beatRateDao.findByCreatedBetweenAndRental(from, to);
    

    IN 子句需要一个不可为空且非空的参数列表,否则查询将失败。

    在 PostgreSQL 上,如果您尝试运行这样的查询:

    select * 
    from product 
    where quantity in ( )
    

    你得到以下错误:

    ERROR:  syntax error at or near ")"
    LINE 3: where quantity in ( )
                                ^
    ********** Error **********
    
    ERROR: syntax error at or near ")"
    SQL state: 42601
    Character: 45
    

    【讨论】:

    • 感谢您的回复。问题是我有几个过滤器。状态,国家,城市,用户......有时国家存在有时不存在,有时你想要状态和国家而不是城市......等等。它会导致很多组合,所以我不确定上述方法是最好的方法吗?.
    • Criteria API 最适合动态过滤器。 Spring Data 不适用于空参数。
    • 什么是 Criteria API?
    • Criteria API 是 JPA 类型安全的动态查询构建器 API。
    • 如果你想构建一个基于任意约束的查询,我建议查看Querydsl。到目前为止,它是动态组装谓词的最佳 API。 Spring Data 派生的查询方法更适用于您有一组静态约束的用例。有关 Spring Data 与 Querydsl 的集成,请参阅 this blog post
    猜你喜欢
    • 2018-07-15
    • 2017-08-06
    • 2017-04-23
    • 2018-11-09
    • 2022-10-13
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多