6.1 Spring Data JPA简介

Spring Data JPA 提供的类、接口有很多,以下关系图中展示了7个接口和2个实现类都是较为常用的,需要掌握。
图中Repository、CrudRepository、PagingAndSortingRepository这三个接口不属于Spring Data JPA,而是位于spring-data-commons包下,是Spring Data的基础接口,兼容SQL、NoSQL;例如Spring Data Redis也依赖该包内的这三个接口。

1
2
3
4
5
6
7
8
9
graph BT
QuerydslJpaRepository-->QuerydslPredicateExecutor
QuerydslJpaRepository-->SimpleJpaRepository
SimpleJpaRepository-->JpaSpecificationExecutor
SimpleJpaRepository-->JpaRepository
JpaRepository-->QueryByExampleExecutor
JpaRepository-->PagingAndSortingRepository
PagingAndSortingRepository-->CrudRepository
CrudRepository-->Repository
入门案列
  1. 新增一个Book查询接口BookRepository
1
2
3
4
5
6
7
package demo.springdao;

import demo.entity.Book;
import org.springframework.data.repository.CrudRepository;

public interface BookRepository extends CrudRepository<Book,Long> {
}
  1. 修改ApplicationContext.xml配置
    增加repositories配置JPA接口所在的包
1
2
3
4
5
6
7
8
9
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:beans="http://www.springframework.org/schema/beans"
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-4.3.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

<jpa:repositories base-package="demo.springdao"/>

</beans>
  1. 调用
    没错就是这么简单,不需要实现类,现在已经可以直接调用CrudRepository接口提供的方法了!
1
2
3
4
5
6
7
8
9
@Autowired
private BookRepository bookRepository;
@Test
public void testSelectBook(){
Iterable<Book> books = bookRepository.findAll();
for (Book book : books ){
System.out.println(book);
}
}