简短说明
当数组列表输入为空时,如何使findBy<Field>In
与IN
一起使用。例如忽略它。你的DAO会是什么样的?
更长的说明。
想象一下,您已创建搜索用户页面。
在申请中。您可以使用各种选项进行过滤。
现在说您要在国家/地区列表中搜索给定日期范围内的所有用户。
搜索用户时,如果我没有选择要搜索所有国家/地区的国家/地区,我将始终搜索已加入的日期。
我打算在国家/地区之外添加几个过滤器选项。因此,我并不想为每个可能的字段组合创建大量的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);
}
答案 0 :(得分:0)
您可以使用两种方法:
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