为什么要运用查询言语?关于任何杂乱的API来说 – 通过十分简略的字段查找 / 过滤资源是不够的。查询言语更灵敏,允许您精确过滤所需的资源。

Query DSL配置

咱们需求将以下依赖项添加到pom.xml:

<dependency>
    <groupId>com.querydsl</groupId> 
    <artifactId>querydsl-apt</artifactId> 
    <version>4.1.4</version>
    </dependency>
<dependency> 
    <groupId>com.querydsl</groupId> 
    <artifactId>querydsl-jpa</artifactId> 
    <version>4.1.4</version> 
</dependency>

咱们还需求配置APT – Annotation处理工具 – 插件如下:

<plugin>
    <groupId>com.mysema.maven</groupId>
    <artifactId>apt-maven-plugin</artifactId>
    <version>1.1.3</version>
    <executions>
        <execution>
            <goals>
                <goal>process</goal>
            </goals>
            <configuration>
                <outputDirectory>target/generated-sources/java</outputDirectory>
                <processor>com.mysema.query.apt.jpa.JPAAnnotationProcessor</processor>
            </configuration>
        </execution>
    </executions>
</plugin>

MyUser Entity

接下来 – 让咱们看一下咱们将在Search API中运用的 MyUser 实体:

@Entity
public class MyUser {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
    private int age;
}

运用PathBuilder自界说Predicate

根据一些恣意束缚创立一个自界说Predicate。

咱们在这里运用PathBuilder而不是自动生成的Q类型,由于咱们需求动态创立途径以取得更笼统的用法:

public class MyUserPredicate {
    private SearchCriteria criteria;
    public BooleanExpression getPredicate() {
        PathBuilder<MyUser> entityPath = new PathBuilder<>(MyUser.class, "user");
        if (isNumeric(criteria.getValue().toString())) {
            NumberPath<Integer> path = entityPath.getNumber(criteria.getKey(), Integer.class);
            int value = Integer.parseInt(criteria.getValue().toString());
            switch (criteria.getOperation()) {
                case ":":
                    return path.eq(value);
                case ">":
                    return path.goe(value);
                case "<":
                    return path.loe(value);
            }
        } 
        else {
            StringPath path = entityPath.getString(criteria.getKey());
            if (criteria.getOperation().equalsIgnoreCase(":")) {
                return path.containsIgnoreCase(criteria.getValue().toString());
            }
        }
        return null;
    }
}

请注意Predicate的完成是一般怎么处理多种类型的操作。这是由于查询言语根据界说是一种开放式言语,您可以运用任何支撑的操作对任何字段进行过滤。

为了表明这种开放式过滤标准,咱们运用了一个简略但十分灵敏的完成 – SearchCriteria:

public class SearchCriteria {
    private String key;
    private String operation;
    private Object value;
}
  • key:用于保存字段称号 – 例如:firstName,age,…等。
  • operation:用于坚持操作 – 例如:Equality,less,…等。
  • value:用于保存字段值 – 例如:john,25,…等。

MyUserRepository

现在 – 让咱们来看看咱们的MyUserRepository。

咱们需求MyUserRepository来扩展QueryDslPredicateExecutor,以便咱们今后可以运用Predicates来过滤查找成果:

public interface MyUserRepository extends JpaRepository<MyUser, Long>,
  QueryDslPredicateExecutor<MyUser>, QuerydslBinderCustomizer<QMyUser> {
    @Override
    default public void customize(
      QuerydslBindings bindings, QMyUser root) {
        bindings.bind(String.class)
          .first((SingleValueBinding<StringPath, String>) StringExpression::containsIgnoreCase);
        bindings.excluding(root.email);
      }
}

结合Predicates

接下来让咱们看看组合Predicates在成果过滤中运用多个束缚。

在以下示例中 – 咱们运用构建器 – MyUserPredicatesBuilder – 来组合Predicates:

public class MyUserPredicatesBuilder {
    private List<SearchCriteria> params;
    public MyUserPredicatesBuilder() {
        params = new ArrayList<>();
    }
    public MyUserPredicatesBuilder with(
      String key, String operation, Object value) {
        params.add(new SearchCriteria(key, operation, value));
        return this;
    }
    public BooleanExpression build() {
        if (params.size() == 0) {
            return null;
        }
        List<BooleanExpression> predicates = new ArrayList<>();
        MyUserPredicate predicate;
        for (SearchCriteria param : params) {
            predicate = new MyUserPredicate(param);
            BooleanExpression exp = predicate.getPredicate();
            if (exp != null) {
                predicates.add(exp);
            }
        }
        BooleanExpression result = predicates.get(0);
        for (int i = 1; i < predicates.size(); i++) {
            result = result.and(predicates.get(i));
        }
        return result;
    }
}

测验查找查询

接下来 – 让咱们测验一下咱们的Search API。

咱们将首先运用少量用户初始化数据库 – 准备好这些数据并进行测验:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class })
@Transactional
@Rollback
public class JPAQuerydslIntegrationTest {
    @Autowired
    private MyUserRepository repo;
    private MyUser userJohn;
    private MyUser userTom;
    @Before
    public void init() {
        userJohn = new MyUser();
        userJohn.setFirstName("John");
        userJohn.setLastName("Doe");
        userJohn.setEmail("john@doe.com");
        userJohn.setAge(22);
        repo.save(userJohn);
        userTom = new MyUser();
        userTom.setFirstName("Tom");
        userTom.setLastName("Doe");
        userTom.setEmail("tom@doe.com");
        userTom.setAge(26);
        repo.save(userTom);
    }
}

接下来,让咱们看看怎么查找具有给定姓氏的用户

@Test
public void givenLast_whenGettingListOfUsers_thenCorrect() {
    MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("lastName", ":", "Doe");
    Iterable<MyUser> results = repo.findAll(builder.build());
    assertThat(results, containsInAnyOrder(userJohn, userTom));
}

现在,让咱们看看怎么找到具有名字和姓氏的用户

@Test
public void givenFirstAndLastName_whenGettingListOfUsers_thenCorrect() {
    MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder()
      .with("firstName", ":", "John").with("lastName", ":", "Doe");
    Iterable<MyUser> results = repo.findAll(builder.build());
    assertThat(results, contains(userJohn));
    assertThat(results, not(contains(userTom)));
}

接下来,让咱们看看怎么找到具有姓氏和最小年龄的用户

@Test
public void givenLastAndAge_whenGettingListOfUsers_thenCorrect() {
    MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder()
      .with("lastName", ":", "Doe").with("age", ">", "25");
    Iterable<MyUser> results = repo.findAll(builder.build());
    assertThat(results, contains(userTom));
    assertThat(results, not(contains(userJohn)));
}

接下来,让咱们查找实际不存在的用户:

@Test
public void givenWrongFirstAndLast_whenGettingListOfUsers_thenCorrect() {
    MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder()
      .with("firstName", ":", "Adam").with("lastName", ":", "Fox");
    Iterable<MyUser> results = repo.findAll(builder.build());
    assertThat(results, emptyIterable());
}

最终 – 让咱们看看怎么找到仅给出名字的一部分的MyUser – 如下例所示:

@Test
public void givenPartialFirst_whenGettingListOfUsers_thenCorrect() {
    MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder().with("firstName", ":", "jo");
    Iterable<MyUser> results = repo.findAll(builder.build());
    assertThat(results, contains(userJohn));
    assertThat(results, not(contains(userTom)));
}

UserController

最终,让咱们将一切内容放在一同并构建REST API。

咱们界说了一个UserController,它界说了一个带有“search”参数的简略办法findAll()来传递查询字符串:

@Controller
public class UserController {
    @Autowired
    private MyUserRepository myUserRepository;
    @RequestMapping(method = RequestMethod.GET, value = "/myusers")
    @ResponseBody
    public Iterable<MyUser> search(@RequestParam(value = "search") String search) {
        MyUserPredicatesBuilder builder = new MyUserPredicatesBuilder();
        if (search != null) {
            Pattern pattern = Pattern.compile("(\w+?)(:|<|>)(\w+?),");
            Matcher matcher = pattern.matcher(search + ",");
            while (matcher.find()) {
                builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
            }
        }
        BooleanExpression exp = builder.build();
        return myUserRepository.findAll(exp);
    }
}

这是一个快速测验URL示例:

http://localhost:8080/myusers?search=lastName:doe,age>25

回应:

[{
    "id":2,
    "firstName":"tom",
    "lastName":"doe",
    "email":"tom@doe.com",
    "age":26
}]