babyachievement / notes

读书笔记
1 stars 1 forks source link

Spring Data JPA (一) #14

Open babyachievement opened 7 years ago

babyachievement commented 7 years ago

1. 核心概念

Spring Data 中核心结构是Repository。Repository接口主要作为标记接口用于捕捉使用的类型,并用于帮助发现继承了此接口的接口。CrudRepository为管理的实体类提供了负载的CRUD功能。

此外Spring Data提供了与特定技术有关的持久化抽象如JpaRepository或MongoRepository。这些接口拓展了CrudRepository,并暴露底层持久化技术的功能,以及通用的技术无关的持久化接口如CrudRepository。

在CrudRepository上层有PagingAndSortingRepository抽象,添加了其他方法简化了分页访问。

如按每页20个获取第二页:

PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(new PageRequest(1, 20));

除了这些查询方法外,还有用于获取数量的查询和删除查询。

public interface UserRepository extends CrudRepository<User, Long> {

  Long countByLastname(String lastname);
}
public interface UserRepository extends CrudRepository<User, Long> {

  Long deleteByLastname(String lastname);

  List<User> removeByLastname(String lastname);

}

2. 查询方法

标准的CRUD功能Repository通常有底层数据的查询。使用Spring Data,声明这些查询只需要四个步骤:

  1. 声明一个继承了Repository或它的一个子接口的接口,然后为其加上它将处理的域类和ID类型。

    interface PersonRepository extends Repository<Person, Long> { … }
  2. 在这个接口中生命查询方法

    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>
  1. 创建被注入的仓库实例并使用它
public class SomeClient {

  @Autowired
  private PersonRepository repository;

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