用途

  1. 可以结合@JpaSelectOperator 使用
  2. 可快速的完成单表的复杂查询
    1. 根据入参对象进行查询条件的封装
      1. where field = value and field2 like ‘%value%’ or field3 <> value

用法示例

使用单例构造 SpecificationUtil

  • and 为 key写死示例
  • and2为根据实体获取key的示例
  1. SpecificationUtil<User> instance = SpecificationUtil.getInstance();
  2. Specification<User> and = instance.like("address", "重庆", true)
  3. .and(instance.eq("name", "用户", true)
  4. .or(instance.eq("loginPwd", "123", true))
  5. .or(instance.eq("phone", "123", true))
  6. .or(instance.eq("userNo", "123", true))
  7. );
  8. Specification<User> and2 = instance.like(User::getAddress, "重庆", true)
  9. .and(instance.eq(User::getName, "用户", true)
  10. .or(instance.eq(User::getLoginPwd, "123", true))
  11. .or(instance.eq(User::getPhone, "123", true))
  12. .or(instance.eq(User::getUserNo, "123", true))
  13. );
  14. userService.getJpaBasicsDao().findAll(and).forEach(System.out::println);

直接使用 Specification

构建查询条件

  1. public static Specification<User> name() {
  2. return (root, query, builder) -> builder.like(root.get("name"), "%用户%");
  3. }
  4. public static Specification<User> loginPwd() {
  5. return (root, query, builder) -> builder.like(root.get("loginPwd"), "123");
  6. }
  7. public static Specification<User> address() {
  8. return (root, query, builder) -> builder.like(root.get("address"), "重庆");
  9. }
  10. public static Specification<User> phone() {
  11. return (root, query, builder) -> builder.like(root.get("phone"), "123");
  12. }
  13. public static Specification<User> userNo() {
  14. return (root, query, builder) -> builder.like(root.get("phone"), "123");
  15. }

使用示例

  1. userService.getJpaBasicsDao().findAll(
  2. address().and(
  3. loginPwd().or(phone()).or(name())
  4. ).or(
  5. loginPwd().and(
  6. phone().or(name())
  7. )
  8. )
  9. ).forEach(System.out::println);