关于mongoTemplate的条件分页查询封装方法

版权声明: https://blog.csdn.net/qq_37105358/article/details/80320148

先上实体类

@Document
@Data        //lombok插件
public class Profile {
    @Id
    private String id;
    @Indexed
    private String userId;
    @Indexed
    private String name;
    private DesignerType type;
    private String pic;
    private Integer sex;
    private String wechat;
    private String qq;
    private String weibo;
    private String description;
    private String address;
    private Date createAt;
    private Date updateAt;
    @Indexed(unique = true)
    private String inviteCode;
    private int inviteCodeUsedCount;
    private Date becomeDesignerDate;
}

以上是实体类,没毛病,get set方法已经通过lombok组件搞定,接着上传查询代码

 public List<Profile> searchProfiles(Integer page, Integer size, String filter) {
        Profile profile = new Profile();
        profile.setName(filter);

        Query query = new Query();
        if (filter!=null && !filter.isEmpty()){
            query.addCriteria(new Criteria().alike(Example.of(profile,
                    ExampleMatcher.matching()
                            .withIgnoreNullValues()
                            .withIgnorePaths("inviteCodeUsedCount")
                            .withIgnoreCase()
                            .withMatcher("name", matcher -> matcher.contains())
            )));
        }
        List<Profile> profiles = mongoTemplate.find(
                query.skip(page * size).limit(size).with(new Sort(Sort.Direction.DESC, "createAt")),
                Profile.class
        );
        return profiles;
    } 

入参分别是页码,每页次数和查询条件,将查询条件封装到实体类,然后创建Query对象,在query对象里添加Criteria对象,做模糊查询,将刚建好的profile实体类传入进去

重点来了,ExampleMatcher.matching()这个代码是进行匹配的,以前压根就没搞过类似的代码,所以一窍不通,其中第一行.

    withIgnoreNullVlaues()意思是忽略空值,字段中有空值的时候要忽略,否则查不出准确的条件查询结果;

    withIgnorePaths(), 这是我踩坑最傻的一次,这个方法的入参要传入所有的有初始值的字段,比如boolean类型的初始值就是false,否则的话是查不到结果集的,我掉进去很长一段时间爬不起来,切记切记!

    后面就不说了,其实我只想说上一个,其余的没必要说了


猜你喜欢

转载自blog.csdn.net/qq_37105358/article/details/80320148