SpringBoot Jpa多条件查询

  • Repository
MyRepository extends JpaRepository<MyEntity, Integer>

精确查询:

Example 包装Entity

Pageable pageable = PageRequest.of(current - 1, pageSize);
//myEntity 实体类参数
Example example = Example.of(myEntity);
Page<MyEntity> page = myRepository.findAll(example, pageable);

 

模糊查询

@Test
    void testQuery() {
        MyEnitty myEnitty = new MyEnitty();

      myEnitty .setUserName("ab");
      myEnitty .setAddress("ef");
      //直接赋值在Matcher没有声明就是会精确匹配
      myEnitty .setAge(18);


        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                //前綴精确匹配ab%
                .withMatcher("userName", ExampleMatcher.GenericPropertyMatcher::startsWith)
                //前后缀都模糊匹配%ef%
                .withMatcher("address", ExampleMatcher.GenericPropertyMatcher::contains);
        Example<MyEnitty> example = Example.of(MyEnitty, exampleMatcher);
        List<MyEnitty> result = MyEnittyRepository.findAll(example);
        for (MyEnitty mt : result) {
            System.out.println(mt.getUserName + ":" + mt.getAddress);
        }
    }

 

  • Specification 支持范围查询

接口继承JpaSpecificationExecutor

extends JpaRepository<MyEntity, Integer>, JpaSpecificationExecutor<MyEntity>

测试

@Test
    void testQuery2() {
        MyEnitty myEnitty = new MyEnitty();
        myEnitty.setId(22);
        myEnitty.setUserName("ab");
        Specification<MyEnitty> specification = (root, query, builder) -> {
            List<Predicate> list = new ArrayList<>();
            //模糊查询
            list.add(builder.like(root.get("userName"), "%"+myEnitty.getUserName()+"%"));
            //范围查询
            list.add(builder.greaterThan(root.get("id"),myEnitty.getId()));
            Predicate[] predicates = new Predicate[list.size()];
            list.toArray(predicates);
            return builder.and(predicates);
        };
        List<MyEnitty> result = myEnittyRepository.findAll(specification);
        for (MyEnitty mt : result) {
            System.out.println(mt.getUserName() + ":" + mt.getAddress());
        }
    }

 



posted @ 2024-05-01 17:17  洞玄巅峰  阅读(593)  评论(0编辑  收藏  举报