您当前的位置: 首页 >  spring

qq_34412985

暂无认证

  • 0浏览

    0关注

    1061博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringDataJPA使用QueryByExample模糊查询遇到的坑

qq_34412985 发布时间:2021-01-10 17:15:31 ,浏览量:0

遇到的情况:在做短信渠道管理添加时,先要去校验数据库中是否有该产线-短信类型-渠道的记录,如果存在就不添加。

//在库中是否存在该记录
    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 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 {
}

使用SpringDataJPA进行模糊查询时:

使用findAll方法传入Example参数;

而Example参数需要根据Entity和ExampleMatcher够造;

ExampleMatcher如上述代码;

特别要注意在Entity中,如果Entity中的属性存在的值(如上述例子中的属性rate存在有效值)在ExampleMatcher中没有进行模糊查询,那么就要让该属性为null(如上述例子:condition.setRate(null) ),否则拼接成的SQL中的where语句中不止有模糊查询like,还有rate=#{rate}的判断。

转载于:https://www.cnblogs.com/theRhyme/p/9149463.html

关注
打赏
1653291990
查看更多评论
立即登录/注册

微信扫码登录

0.0476s