MyRepository extends JpaRepository<MyEntity, Integer>
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);
}
}
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());
}
}