4.2 查询方法

优质
小牛编辑
121浏览
2023-12-01

标准的CRUD(增删改查)功能都要使用查询语句来查询数据库。但通过使用Spring Data,只要四个步骤就可以实现。

1.声明一个继承Repository接口或其子接口的持久层接口。并标明要处理的域对象类型及其主键的类型(在下面的例子中,要处理的域对象是Person,其主键类型是Long)

interface PersonRepository extends Repository<Person, Long> {...}

2.在接口中声明查询方法(spring会为其生成实现代码)

interface PersonRepository extends Repository<Person, Long> {
  List<Person> findByLastname(String lastname);
}

3.让Spring创建对这些接口的代理实例。
通过JavaConfig

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EnableJpaRepositories
class Config {}

通过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
     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的命名空间作为例子,需要根据实际使用的模块更改命名空间,比如可以改为mongodb等等。需要注意的是,在使用JavaConfig时,如果需要自定义扫描的包而不是使用其默认值,可以利用注解@EnableJpaRepositories的basePackage属性。具体使用方式如下:

@EnableJpaRepositories(basePackages = "com.cshtong")//单个包
@EnableJpaRepositories(basePackages = {"com.cshtong.sample.repository", "com.cshtong.tower.repository"})//多个包路径

4.注入repository实例,并使用

public class SomeClient {

  @Autowired
  private PersonRepository repository;

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

这一部分会在之后详细解释