1. 程式人生 > >SpringDataJPA模糊查詢

SpringDataJPA模糊查詢

語句 拼接 lean list ctc int contain tty spa

遇到的情況:在做短信渠道管理添加時,先要去校驗數據庫中是否有該產線-短信類型-渠道的記錄,如果存在就不添加。

//在庫中是否存在該記錄
    private boolean ifExistChannelConfig(SmsChannelProductConfig smsChannelProductConfig){
        ExampleMatcher matcher = ExampleMatcher.matching() //構建對象
                .withMatcher("product", ExampleMatcher.GenericPropertyMatchers.contains()) //
產線采用“like”的方式查詢 .withMatcher("channel", ExampleMatcher.GenericPropertyMatchers.contains()) //渠道采用“like”的方式查詢 .withMatcher("type", ExampleMatcher.GenericPropertyMatchers.contains()) //短信類型采用“like”的方式查詢 .withIgnorePaths("focus"); //忽略屬性:是否關註。因為是基本類型,需要忽略掉 SmsChannelProductConfig condition
= new SmsChannelProductConfig(); condition.setProduct(smsChannelProductConfig.getProduct()); condition.setChannel(smsChannelProductConfig.getChannel()); condition.setType(smsChannelProductConfig.getType()); condition.setRate(null);//不允許匹配權重查詢 List<SmsChannelProductConfig> list = smsChannelProductConfigRepository.findAll(Example.of(condition, matcher));
if(list == null){ return false; }else if(list.isEmpty()){ return false; }else{ return true; } }
public interface SmsChannelProductConfigRepository extends JpaRepository<SmsChannelProductConfig, Long> {
}

使用SpringDataJPA進行模糊查詢時:

使用findAll方法傳入Example參數;

而Example參數需要根據EntityExampleMatcher夠造;

ExampleMatcher如上述代碼;

特別要註意在Entity中,如果Entity中的屬性存在的值(如上述例子中的屬性rate存在有效值)在ExampleMatcher中沒有進行模糊查詢,那麽就要讓該屬性為null(如上述例子:condition.setRate(null) ),否則拼接成的SQL中的where語句中不止有模糊查詢like,還有rate=#{rate}的判斷。

SpringDataJPA模糊查詢