1. 如何使用 Spring Data JPA ?
核心接口Repository ,Spring在此接口上使用了**@Indexed**注解
在继承了Repository接口的公共接口上使用了NoRepositoryBean注解
1.业务中要实现实体类增删改查,则要新建自己的接口去继承Repository接口或者去继承Repository接口的子接口,自己新建的接口需要把要操作的实体类和该类的主键类型作为泛型
interface PersonRepository extends Repository<Person, Long> { … }
2.在自己建的接口里面定义操作实体类的增删改查方法
interface PersonRepository extends Repository<Person, Long> {
List<Person> findByLastname(String lastname);
}
3.设置Spring以使用JavaConfig或XML配置为这些接口创建代理实例
3.1 JavaConfig方式,@EnableJpaRepositories注解
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EnableJpaRepositories
class Config {}
3.2 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>
4.注入存储库实例并使用它
class SomeClient {
private final PersonRepository repository;
SomeClient(PersonRepository repository) {
this.repository = repository;
}
void doSomething() {
List<Person> persons = repository.findByLastname("Matthews");
}
}
以上就是使用Spring Data JPA的4个步骤,总结如下:
- 定义存储库接口:继承Repository接口
- 定义查询方法:根据JPA语法定义查询方法
- 创建存储库实例:配置JavaConfig或者XML让Spring自动注入接口的实例
- Spring数据存储库的自定义实现
1.2 区分数据模块(数据库MySQL、MonogoDB)的方法
- 看自己定义的接口继承的接口是哪个数据模块的
// JPA
interface MyRepository extends JpaRepository<User, Long> { }
@NoRepositoryBean
interface MyBaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
…
}
interface UserRepository extends MyBaseRepository<User, Long> {
…
}
- 看实体类的注解使用的是什么数据模块的注解
interface PersonRepository extends Repository<Person, Long> {
…
}
// JPA数据模块
@Entity
class Person {
…
}
interface UserRepository extends Repository<User, Long> {
…
}
//mongoDB数据模块
@Document
class User {
…
}
- 看自己定义的接口所在的包,包定义了扫描接口定义
@EnableJpaRepositories(basePackages = "com.acme.repositories.jpa")//定义在这个包里的接口是JPA数据模块
@EnableMongoRepositories(basePackages = "com.acme.repositories.mongo")//定义在这个包里的接口是mongodb数据模块
interface Configuration { }