SpingDataJPA之ExampleMatcher实例查询

ExampleMatcher是SpingData-JPA中好玩的一个东西

ExampleMatcher实例查询三要素

  • 实体对象:在ORM框架中与Table对应的域对象,一个对象代表数据库表中的一条记录,如上例中User对象,对应user表。在构建查询条件时,一个实体对象代表的是查询条件中的“数值”部分。如:要查询姓“X”的客户,实体对象只需要存储条件值“X”。

  • 匹配器:ExampleMatcher对象,它是匹配“实体对象”的,表示了如何使用“实体对象”中的“值”进行查询,它代表的是“查询方式”,解释了如何去查的问题。如:要查询姓“X”的客户,即姓名以“X”开头的客户,该对象就表示了“以某某开头的”这个查询方式,如上例中:withMatcher(“userName”, GenericPropertyMatchers.startsWith())

  • 实例:即Example对象,代表的是完整的查询条件。由实体对象(查询条件值)和匹配器(查询方式)共同创建。最终根据实例来findAll即可。

    /** * 查询失物招领信息 * @return */
    @GetMapping("/lost/list")
    public ApiReturnObject findAllLostProperty (String materialName,Timestamp registerTime,String status) {
        LostProperty obj=new LostProperty();
        obj.setMaterialName(materialName);
        obj.setRegisterTime(registerTime);
        obj.setStatus(status);
        //创建匹配器,即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withMatcher("materialName", GenericPropertyMatchers.contains()) //姓名采用“开始匹配”的方式查询
                .withMatcher("registerTime", GenericPropertyMatchers.contains()) //姓名采用“开始匹配”的方式查询
                .withMatcher("status", GenericPropertyMatchers.contains()) //姓名采用“开始匹配”的方式查询
                .withIgnorePaths("id");  //忽略属性:是否关注。因为是基本类型,需要忽略掉

        //创建实例
        Example<LostProperty> ex = Example.of(obj, matcher); 
        //查询
        List<LostProperty> ls = lostPropertyRespository.findAll(ex);

        return ApiReturnUtil.success(ls);
    }

查询状态为0的全部
《SpingDataJPA之ExampleMatcher实例查询》
查询状态为0,且名字为手机的
《SpingDataJPA之ExampleMatcher实例查询》

Matching生成的语句说明

  • DEFAULT (case-sensitive) firstname = ?0 默认(大小写敏感)
  • DEFAULT (case-insensitive) LOWER(firstname) = LOWER(?0) 默认(忽略大小写)
  • EXACT (case-sensitive) firstname = ?0 精确匹配(大小写敏感)
  • EXACT (case-insensitive) LOWER(firstname) = LOWER(?0) 精确匹配(忽略大小写)
  • STARTING (case-sensitive) firstname like ?0 + ‘%’ 前缀匹配(大小写敏感)
  • STARTING (case-insensitive) LOWER(firstname) like LOWER(?0) + ‘%’ 前缀匹配(忽略大小写)
  • ENDING (case-sensitive) firstname like ‘%’ + ?0 后缀匹配(大小写敏感)
  • ENDING (case-insensitive) LOWER(firstname) like ‘%’ + LOWER(?0) 后缀匹配(忽略大小写)
  • CONTAINING (case-sensitive) firstname like ‘%’ + ?0 + ‘%’ 模糊查询(大小写敏感)
  • CONTAINING (case-insensitive) LOWER(firstname) like ‘%’ + LOWER(?0) + ‘%’ 模糊查询(忽略大小写)

后话

使用一段时间之后,发现ExampleMatcher对日期的查询很不友好,不支持动态查询的,所以有了接下来研究的Specification复杂查询,可以了解一下。

SpringDataJpa之Specification复杂查询
https://blog.csdn.net/moshowgame/article/details/80309642

SpringDataJpa之Pageable+ExampleMatcher进行分页多条件查询
https://blog.csdn.net/moshowgame/article/details/80650641

    原文作者:Moshow郑锴
    原文地址: https://blog.csdn.net/moshowgame/article/details/80282813
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞