3.2. 查询方法
Standard CRUD functionality repositories usually have queries on the underlying datastore. With Spring Data, declaring those queries becomes a four-step process:
标准的CRUD函数库通常会在底层存储上定义一些列方法。使用Spring-Data声明一个这样的方法只需要4个步骤:
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.
1、声明一个接口,这个接口需要继承Repository或它的子接口,并向这个接口泛型传递两个参数,一个是被管理的实体类,一个是实体类的主键(id type)。
interface PersonRepository extends Repository<Person,Long>{
...
}
2.Declare query methods on the interface:
2、在接口中声明方法:
interface PersonRepository extends Repository<Person,Long>{
List<Person> findByLastname(String lastname);
}
3.Set up Spring to create proxy instances for those interfaces. Either via JavaConfig:
3、配置Spring以创建这些接口的代理实例。可以选择Java配置,
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EnableJpaRepositories
class Config{}
或者是XML配置:
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="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>
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. 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.
这里使用了JPA的命名空间作为例子。如果使用的是其他支持JPA 存储,如MongoDB,就需要改成相应的命名空间。 另外需要注意,通过javaconfig并没有配置base-package属性,应用程序将扫描所有的默认注解
@Repository。如果需要自定义包扫描路径请在@EnableJpaRepositories注解中配置basepackage属性。
4.Get the repository instance injected and use it:
4、注入repository 的实例并使用:
public class SomeClient{
@Autowired
private PersonRepository repository;
public void doSomething(){
List<Person> persons = repository.findByLastname("Matthews");
}
}
The sections that follow explain each step in detail.
后面的章节将对每个步骤做更详细的说明。