您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring Boot和JPA:使用可选的范围内条件实现搜索查询

Spring Boot和JPA:使用可选的范围内条件实现搜索查询

您可以通过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中存在的完整示例

您也可以使用规范创建任何复杂的查询

Java 2022/1/1 18:22:06 有551人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶