QueryByExampleExecutor
可以通过实体进行简单的查询。比如我们查询用于昵称是超级
开头的用户。
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private SysUserRepository sysUserRepository;
@GetMapping("/findAll")
@Transactional
public List<SysUser> findAll() {
SysUser sysUser = new SysUser();
sysUser.setNickName("超级");
ExampleMatcher exampleMatcher = ExampleMatcher.matching()
.withMatcher("nickName", ExampleMatcher.GenericPropertyMatchers.startsWith())
.withIgnorePaths("focus");
Example<SysUser> sysUserExample = Example.of(sysUser, exampleMatcher);
return sysUserRepository.findAll(sysUserExample);
}
}
其实跟MyBatis-Plus
类似,功能比较简单,只能拼接and
查询,一般使用不是很多。
JpaSpecificationExecutor
使用Specification的要点就是CriteriaBuilder,通过这个对象来创建条件,之后返回一个Predicate对象。这个对象中就有了相应的查询需求,我们同样可以定义多个Specification,之后通过Specifications对象将其连接起来。
修改接口
public interface SysUserRepository extends JpaRepository<SysUser, Long>, JpaSpecificationExecutor<SysUser> {
}
测试
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private SysUserRepository sysUserRepository;
@GetMapping("/findAll")
@Transactional
public List<SysUser> findAll() {
return sysUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
Predicate p1 = criteriaBuilder.like(root.get("nickName"), "%超级%");
Predicate p2 = criteriaBuilder.equal(root.get("userName"), "admin");
Predicate p3 = criteriaBuilder.equal(root.get("email"),"ry@163.com");
return criteriaBuilder.and(p1, p2);
});
}
}
评论 (0)