以实际项目需求展示方法使用
Entity 实体类
@Entity
@Data
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String company;
private String address;
}
Controller 层
@RestController
@RequestMapping("/api/person")
public class PersonController {
private final PersonService personService;
@Autowired
public PersonController(PersonService personService) {
this.personService = personService;
}
@GetMapping
public Page<Person> findAll(Person person, Pageable pageable) {
return personService.findAll(person, pageable);
}
}
Service 层
@Service
public class PersonService {
private final PersonRepository personRepository;
@Autowired
public PersonService(PersonRepository personRepository) {
this.personRepository = personRepository;
}
public Page<Person> findAll(Person person, Pageable pageable) {
ExampleMatcher matcher = ExampleMatcher.matching()
.withMatcher("name", match -> match.contains())
.withMatcher("company", match -> match.contains());
Example<Person> example = Example.of(person, matcher);
return personRepository.findAll(example, pageable);
}
}
Repository 层
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {}
PostMan 测试结果
![PostMan 测试](https://i-blog.csdnimg.cn/blog_migrate/570f5b831289c597c3cb15220ef734e3.png)
总结
QueryByExampleExecutor
接口仅适合简单的动态分页查询,对日期动态查询不够友好