栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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中存在的完整示例

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/372519.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号