如何在Spring-boot中编写基于多个查询过滤器的通用Java函数以查询结果

时间:2018-07-01 03:45:23

标签: spring-boot jpa

我正在使用jdo开发Java,在Java中我曾编写过如下查询函数,该查询函数根据传递给函数的参数从Entity进行查询。 现在我正在使用spring-boot,并想知道我是否可以使用spring-boot达到同样的效果。任何帮助或建议将不胜感激。谢谢!

public List<Result> getQueryResult(int filter1, String filter2,Float filter3,Long id){
    Query query = new Query("select from Entity1");
    String filter = "id == "+id;
    if(filter1 != null){
      filter = filter+" && filter1 == "+filter1+";
    }
    if(filter2 != null){
    filter = filter+" && filter2 == '"+filter2+"'";
    }
    if(filter3 != null){
    filter = filter+"filter3 == "+filter3;
    }
    query.setFIlter(filter);
    List<Result> results = query.excute();
    return results;
    }                  

1 个答案:

答案 0 :(得分:1)

您有两个选择-您可以使用JPA Criteria BuilderJPA Specifications

class Person {
  String firstName;
  String lastName;
  int age;
}

JPA标准构建器

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Person> query = builder.createQuery(Person.class);
Root<Person> root = query.from(Person.class);

Predicate sellAlcohol = builder.ge(root.get(Person_.age), 21);
Predicate toMindy = builder.equal(root.get(Person_.firstName), "Mindy");

用法

query.where(builder.and(sellAlcohol, toMindy));
em.createQuery(query.select(root)).getResultList();

规格

public PersonSpecifications {

  public static Specification<Person> sellAlcohol() {
    return new Specification<Person> {
      public Predicate toPredicate(Root<T> root, CriteriaQuery query, CriteriaBuilder cb) {
        return cb.ge(root.get(Person_.age), 21);
      }
    };
  }

  public static Specification<Person> toMindy() {
    return new Specification<Person> {
      public Predicate toPredicate(Root<T> root, CriteriaQuery query, CriteriaBuilder cb) {
        return cb.equal(root.get(Person_.firstName), "Mindy");
      }
    };
  }
}

用法

personRepository.findAll(where(sellAlcohol()).and(toMindy()));