3.2 查询方法

3.2 查询方法

3.2. Query methods

标准CRUD功能库通常都有各种查询。在Spring Data中,声明这些查询需要四个步骤:

Standard CRUD functionality repositories usually have queries on the underlying datastore. With Spring Data, declaring those queries becomes a four-step process:

  1. 继承Repository或者它的一个子接口来声明一个接口,并定义其需要处理的域类的类型与ID类型。
  1. Declare an interface extending Repository or one of its subinterfaces and type it to the domain class and ID type that it will handle.
interface PersonRepository extends Repository<Person, Long> { … }
  1. 在此接口中声明查询方法。
  1. Declare query methods on the interface.
interface PersonRepository extends Repository<Person, Long> {
  List<Person> findByLastname(String lastname);
}
  1. 设置Spring来创建这些接口的代理。或者通过JavaConfig
  1. Set up Spring to create proxy instances for those interfaces. Either via JavaConfig:
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EnableJpaRepositories
class Config {}

或者通过XML配置

or via XML configuration:

<?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
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/data/jpa
     http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

   <jpa:repositories base-package="com.acme.repositories"/>

</beans>

在此例中使用了JPA命名空间。如果你使用了其他的库抽象,你需要改为设置合适的命名空间来声明你的存储模块,例如将jpa替换为mongodb

The JPA namespace is used in this example. If you are using the repository abstraction for any other store, you need to change this to the appropriate namespace declaration of your store module which should be exchanging jpa in favor of, for example, mongodb.

同样要注意JavaConfig变体不会配置一个精确指向注解类的包。需要使用一个指定数据库的@Enable…注解中的basePackage…注解来自定义包扫描。

Also, note that the JavaConfig variant doesn’t configure a package explictly as the package of the annotated class is used by default. To customize the package to scan use one of the basePackage… attribute of the data-store specific repository @Enable…-annotation.

  1. 注意库实例并使用
  1. Get the repository instance injected and use it.
class SomeClient {

  private final PersonRepository repository;

  SomeClient(PersonRepository repository) {
    this.repository = repository;
  }

  void doSomething() {
    List<Person> persons = repository.findByLastname("Matthews");
  }
}

下一节将详述每一步。

The sections that follow explain each step in detail.

翻译部分版权归YahaCode团队所有。仅供学习研究之用,任何组织或个人不得私自以此用于任何形式的商业目的

发表评论