我正在使用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;
}
答案 0 :(得分:1)
您有两个选择-您可以使用JPA Criteria Builder或JPA Specifications
class Person {
String firstName;
String lastName;
int age;
}
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()));