Spring Data JPA - 查询创建(1)基本步骤

作者简介

陈喆,现就职于中科院某研究所担任副研究员,专注于工业云平台、MES系统的设计与研发。

内容来源:https://docs.spring.io/spring-data/jpa/docs/2.0.9.RELEASE/reference/html/#repositories.query-methods

标准的CRUD功能仓库都都包含对底层数据库的查询方法。使用Spring Data,声明这些方法需要四个步骤:

1. 声明一个扩展Repository或其子类的接口,并标明实体类和ID的类型:

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

2. 在接口中声明查询方法

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

3. 使用JavaConfigXML configuration创建这些接口的代理实例

a. 使用Java配置

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
     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命名空间。如果你使用的时其它数据存储的repository,你需要修改到相应的命名空间上。

4. 注入repository实例,然后使用它

class SomeClient {

  private final PersonRepository repository;

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

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

猜你喜欢

转载自blog.csdn.net/gavinabc/article/details/81774052