您可以通过JpaSpecificationExecutor
使用Spring数据来实现具有规范的复杂查询。存储库接口必须扩展该JpaSpecificationExecutor<T>
接口,以便我们可以通过创建新Specification<T>
对象来指定数据库查询的条件。
诀窍是将Specification接口与结合使用JpaSpecificationExecutor
。这是示例:
@Entity
@Table(name = "person")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "surname")
private String surname;
@Column(name = "city")
private String city;
@Column(name = "age")
private Integer age;
....
}
然后,我们定义存储库:
public interface PersonRepository extends JpaRepository<Person, Long>, JpaSpecificationExecutor<Person> {
}
如您所见,我们扩展了另一个接口JpaSpecificationExecutor
。该接口定义了通过规范类执行搜索的方法。
现在,我们要做的是定义我们的规范,该规范将返回Predicate
包含查询约束的规范(在示例中,PersonSpecification
执行查询的select * from name =?或(surname =?and age =?)的人员):
public class PersonSpecification implements Specification<Person> {
private Person filter;
public PersonSpecification(Person filter) {
super();
this.filter = filter;
}
public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> cq,
CriteriaBuilder cb) {
Predicate p = cb.disjunction();
if (filter.getName() != null) {
p.getExpressions()
.add(cb.equal(root.get("name"), filter.getName()));
}
if (filter.getSurname() != null && filter.getAge() != null) {
p.getExpressions().add(
cb.and(cb.equal(root.get("surname"), filter.getSurname()),
cb.equal(root.get("age"), filter.getAge())));
}
return p;
}
}
现在是时候使用它了。以下代码片段显示了如何使用我们刚刚创建的规范:
…
Person filter = new Person();
filter.setName("Mario");
filter.setSurname("Verdi");
filter.setAge(25);
Specification<Person> spec = new PersonSpecification(filter);
List<Person> result = repository.findAll(spec);
这是github中存在的完整示例
您也可以使用规范创建任何复杂的查询