SpringDataJPA模糊查詢遇到的坑


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

//在庫中是否存在該記錄
    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}的判斷。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM