Spring JPA 查询

时间:2022-07-24
本文章向大家介绍Spring JPA 查询,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Spring JPA 查询

翻译:Query methods

​ 标准CRUD功能存储库通常在基础数据存储上进行查询。使用Spring Data,声明这些查询将分为四个步骤:

  1. 声明一个继承于Repository 的接口或一个他的子接口,并且绑定其类(Person)和对应ID类型(Long),如下所示: interface PersonRepository extends Repository<Person, Long> { … }
  2. 在接口中声明查询方法 interface PersonRepository extends Repository<Person, Long> { List<Person> findByLastname(String lastname); }
  3. 配置Spring项目为这些接口配置代理实例,使用JavaConfig或者XML a.JavaConfig配置形式 import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @EnableJpaRepositories class Config { … } b.xml配置形式 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa https://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <jpa:repositories base-package="com.acme.repositories"/> </beans>

​ 在此示例中使用了JPA命名空间。如果将存储库抽象用于任何其他数据访问控制,则需要将其更改为数据访问模块的相对应的名称空间声明。换句话说,如果访问的是MogoDB的话,您应该将jpa换成mongodb

  1. 注入存储库实例并使用它 class SomeClient { private final PersonRepository repository; SomeClient(PersonRepository repository) { this.repository = repository; } void doSomething() { List<Person> persons = repository.findByLastname("Matthews"); } }