SpringBoot Jpa多條件查詢

洞玄巅峰發表於2024-05-01
  • 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);
        }
    }



相關文章