我正在尝试通过几个参数找到表格的必要元素,例如
List <Person> findByLastname(String lastname);
但是如果未来添加/删除了某些参数怎么办?如何使用Spring Data JPA使一些参数变得可选,类似于以下内容:
List <Person> findByOptionalLastnameAndOptionalFirstNameAnd...(String lastname, String firstname,...);
我正在尝试通过几个参数找到表格的必要元素,例如
List <Person> findByLastname(String lastname);
但是如果未来添加/删除了某些参数怎么办?如何使用Spring Data JPA使一些参数变得可选,类似于以下内容:
List <Person> findByOptionalLastnameAndOptionalFirstNameAnd...(String lastname, String firstname,...);
我使用querydsl框架解决了我的任务。如果您使用gradle,您需要在build.gradle中添加这个:
dependencies {
compile "com.mysema.querydsl:querydsl-jpa:3.6.3"
compile "com.mysema.querydsl:querydsl-apt:3.6.3:jpa" // Magic happens here
compile "org.hibernate:hibernate-entitymanager:4.3.5.Final"
compile 'com.h2database:h2:1.4.187'
}
还可以使用JPA Criteria API,一个很好的示例在这里,而一个很好的教程则在这里。
@Entity
public class A {
@Id private Long id;
String someAttribute;
String someOtherAttribute;
...
}
查询本身:
//some parameters to your method
String param1 = "1";
String paramNull = null;
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery cq = qb.createQuery();
Root<A> customer = cq.from(A.class);
//Constructing list of parameters
List<Predicate> predicates = new ArrayList<Predicate>();
//Adding predicates in case of parameter not being null
if (param1 != null) {
predicates.add(
qb.equal(customer.get("someAttribute"), param1));
}
if (paramNull != null) {
predicates.add(
qb.equal(customer.get("someOtherAttribute"), paramNull));
}
//query itself
cq.select(customer)
.where(predicates.toArray(new Predicate[]{}));
//execute query and do something with result
em.createQuery(cq).getResultList();
使用示例查询
Person person = new Person();
person.setLastname("Smith");
Example<Person> example = Example.of(person);
List<Person> results = personRepository.findAll(example);
文档 http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example
这是Adam Erstelle对于Spring Data JPA: Query by Example?的回答。
如果您不确定自己的参数是否固定,那么我会使用以下方法:
使用Spring规范,您可以根据某些条件构建查询。 https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
创建一些JUnit测试,确保您的查询是稳定的,并且如果有人添加/删除某些参数,则应修改JUnit以使其保持更新。
如果您对如何使用有疑问,请告诉我,我可以与您分享其他示例。
@RequestMapping("find")
public List<Person> findByOptional...(@RequestParam(value = "fName", required = false) String fname,@RequestParam(value = "lName", required = false) String lname) {
//here you need to check you data for not null and create methods accordingly
}
但这并不是一个好的建议,如果你传递了更多的可选参数,那么就需要放置更多的if else条件语句。