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}的判断。

猜你喜欢

转载自www.cnblogs.com/theRhyme/p/9149463.html