简介
SpringData JPA是 JPA的一种实现,极大的简化了JPA的开发,原始JPA的开发,需要创建实体管理工厂,使用实体管理器定义各种查询进行CRUD操作,而SpringData JPA只需要通过核心接口Repository和它的子类就能很方便的操作数据库。
Repository
1. Repository:最顶层的接口,一个空的接口,统一所有的Repository类型,并且能够让组件扫描的时候能够自动识别
2. CrudRepository: Repository的子接口,提供CRUD的操作
3. PagingAndSortingRepository: CrudRepository的子接口,添加了分页和排序的功能
4. JpaRepository: 是PagingAndSortingRepository的子接口,增加一些实用的功能,比如批量操作
5. JpaSpecificationExecutor:来定义复杂查询
使用SpringData JPA
将SpringDataJPA整合Spring,将EntityManagerFactory的创建交给Spring容器,只需要在xml中配置JPA的Repository的接口位置,就可以很方便的获取到Repository的bean,使用时候直接在service层注入定义的repository.
配置文件:
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="cn.bing"/>
<!-- 配置数据库资源文件的位置-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- jdbc.properties 中的key必须定义为 jdbc.username,格式开头的 -->
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driverClassName}"/>
</bean>
<!-- 2. 配置 JPA 的 EntityManagerFactory -->
<bean id="entityManagerFactory"