提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
Spring data JPA
前言
介绍
官网:https://spring.io/projects/spring-data-jpa#overview
Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered
applications that use data access technologies.
Implementing a data access layer of an application has been cumbersome for quite a while. Too much boilerplate code
has to be written to execute simple queries as well as perform pagination, and auditing. Spring Data JPA aims to
significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually
needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the
implementation automatically.
Spring Data JPA 是更大的 Spring Data 系列的一部分,可以轻松实现基于 JPA 的repositories。该模块处理对基于 JPA 的数据访
问层的增强支持。它使构建使用数据访问技术的 Spring 驱动的应用程序变得更加容易。
实现应用程序的数据访问层已经很麻烦了。必须编写太多样板代码来执行简单的查询以及执行分页和审计。Spring Data JPA 旨在改
进数据访问层的实现以提升开发效率。作为开发人员,您编写存储库接口,包括自定义 finder 方法,Spring 将自动提供实现。
人话
spirng data jpa是spring提供的一套简化JPA开发的框架,按照约定好的规则进行【方法命名】去写dao层接口,就可以
在不写接口实现的情况下,实现对数据库的访问和操作。同时提供了很多除了CRUD之外的功能,如分页、排序、复杂查
询等等。
Spring Data JPA 让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作工程中,推荐使
用Spring Data JPA + ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使
数据库层操作更加简单,方便解耦
特性
SpringData Jpa 极大简化了数据库访问层代码。 如何简化的呢? 使用了SpringDataJpa,我们的dao层中只需要写接
口,就自动具有了增删改查、分页查询等方法
一、Spring Data JPA实例
我们来实现一个基于Spring Data JPA的示例感受一下和之前单独使用的区别:
依赖
1.最好在父maven项目中设置spring data统一版本管理依赖: 因为不同的spring data子项目发布时间版本不一样,你自
己维护很麻烦, 这样不同的spring data子项目能保证是统一版本.
二、使用步骤
1.引入父级库
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tuling.springdata</groupId>
<artifactId>springdata</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>01-springdata-jpa</module>
<module>02-springdata-jpa</module>
<module>03-springdata-jpa</module>
</modules>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--统一管理SpringData子项目的版本-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-bom</artifactId>
<version>2021.1.0</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
</project>
2.引入项目的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>SpringData-JAP</artifactId>
<groupId>com.springData</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>SpringDataJPA01</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<querydsl.version>4.4.0</querydsl.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<!-- junit4 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- hibernate对jpa的支持包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.32.Final</version>
</dependency>
<!-- Mysql and MariaDB -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!--spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.10</version>
<scope>test</scope>
</dependency>
<!-- querydsl -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>${querydsl.version}</version>
</dependency>
</dependencies>
</project>
方式一:通过xml的方式配置spring.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" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
https://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--用于整合jpa @EnableJpaRepositories -->
<jpa:repositories base-package="com.tuling.repositories"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager"
/>
<!--EntityManagerFactory-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<!--Hibernate实现-->
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--生成数据库表-->
<property name="generateDdl" value="true"></property>
<property name="showSql" value="true"></property>
</bean>
</property>
<!--设置实体类的包-->
<property name="packagesToScan" value="com.tuling.pojo"></property>
<property name="dataSource" ref="dataSource" ></property>
</bean>
<!--数据源-->
<bean class="com.alibaba.druid.pool.DruidDataSource" name="dataSource">
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/springdata_jpa?characterEncoding=UTF-8"/>
</bean>
<!--声明式事务-->
<bean class="org.springframework.orm.jpa.JpaTransactionManager" name="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<!--启动注解方式的声明式事务-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
方法二:通过Config配置
package com.zuxia.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration // 标记当前类为配置类 =xml配文件
//@EnableJpaRepositories(basePackages="com.zuxia.repositories") // 启动jpa <jpa:repositories
@EnableTransactionManagement // 开启事务
public class SpringDataJPAConfig {
/*
* <!--数据源-->
<bean class="com.alibaba.druid.pool.DruidDataSource" name="dataSource">
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/springdata_jpa?characterEncoding=UTF-8"/>
</bean>
* */
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/springdata_jpa?characterEncoding=UTF-8");
return dataSource;
}
/*
* <!--EntityManagerFactory-->
<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<!--Hibernate实现-->
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--生成数据库表-->
<property name="generateDdl" value="true"></property>
<property name="showSql" value="true"></property>
</bean>
</property>
<!--设置实体类的包-->
<property name="packagesToScan" value="com.zuxia.pojo"></property>
<property name="dataSource" ref="dataSource" ></property>
</bean>
* */
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.tuling.pojo");
factory.setDataSource(dataSource());
return factory;
}
/*
* <bean class="org.springframework.orm.jpa.JpaTransactionManager" name="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
* */
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
}
3.SpringDataJPA的CRUD
3.1创建RepositoryCRUD接口
package com.zuxia.repositories;
import com.zuxia.pojo.Customer;
import org.springframework.data.repository.CrudRepository;
/**
* 创建RepositoryCRUD接口
*/
public interface CustomerRepository extends CrudRepository<Customer,Long> {
}
3.2.测试类
package com.tuling;
import com.tuling.config.SpringDataJPAConfig;
import com.tuling.pojo.Customer;
import com.tuling.repositories.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.Optional;
// 基于junit4 spring单元测试
//@ContextConfiguration("/spring.xml")
@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringdataJpaTest {
// jdk动态代理的实例
@Autowired
CustomerRepository repository;
@Test
public void testR(){
Optional<Customer> byId = repository.findById(20L);
System.out.println(byId.orElse(null));
}
@Test
public void testC(){
Customer customer = new Customer();
customer.setCustName("李四");
System.out.println(repository.save(customer));
}
@Test
public void testD(){
Customer customer = new Customer();
customer.setCustId(3L);
customer.setCustName("李四");
repository.delete(customer);
}
@Test
public void testFindAll(){
Iterable<Customer> allById = repository.findAllById(Arrays.asList(1L, 7L, 8L));
System.out.println(allById);
}
}
4.使用SpringDataJPA的Repositorys
Spring Data repository 抽象的目标是显着减少为各种持久性存储实现数据访问层所需的样板代码量。
CrudRepository
// 用来插入和修改 有主键就是修改 没有就是新增
// 获得插入后自增id, 获得返回值
<S extends T> S save(S entity);
// 通过集合保存多个实体
<S extends T> Iterable<S> saveAll(Iterable<S> entities);
// 通过主键查询实体
Optional<T> findById(ID id);
// 通过主键查询是否存在 返回boolean
boolean existsById(ID id);
// 查询所有
Iterable<T> findAll();
// 通过集合的主键 查询多个实体,, 返回集合
Iterable<T> findAllById(Iterable<ID> ids);
// 查询总数量
long count();
// 根据id进行删除
void deleteById(ID id);
// 根据实体进行删除
void delete(T entity);
// 删除多个
void deleteAllById(Iterable<? extends ID> ids);
// 删除多个传入集合实体
void deleteAll(Iterable<? extends T> entities);
// 删除所有
void deleteAll();
在 之上CrudRepository,有一个PagingAndSortingRepository抽象,它添加了额外的方法来简化对实体的分页和排序访问:
//分页
Page<Customer> all=findAll(PageRequest.of(0, 2));
System.out.println(all.getTotalPages());//获取总页数
System.out.println(all.getTotalElements());//获取总数量
System.out.println(all.getContent());//获取当前页的所有数据
//分页+排序
Page<Customer> all = repository.findAll(PageRequest.of(页数, 每页显示的数量,Sort.by("排序的字段").descending()));
//排序
Sort sort = Sort.by("custId").descending();
Iterable<Customer> all = repository.findAll(sort);
// 类型安全的方式排序
Sort.TypedSort<Customer> sortType = Sort.sort(Customer.class);
Sort sort = sortType.by(Customer::getCustId).descending();
Iterable<Customer> all = repository.findAll(sort);
package com.zuxia.repositories;
import com.zuxia.pojo.Customer;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* PagingAndSortingRepository拥有分页和排序的能力
*/
public interface CustomerRepository extends PagingAndSortingRepository<Customer,Long> {
}
测试类
package com.tuling;
import com.tuling.config.SpringDataJPAConfig;
import com.tuling.pojo.Customer;
import com.tuling.repositories.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Optional;
@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringDataJpaPagingAndSortTest
{
// jdk动态代理的实例
@Autowired
CustomerRepository repository;
/**
* 分页
*/
@Test
public void testPaging(){
/*分页+排序*/
Page<Customer> all = repository.findAll(PageRequest.of(0, 2,Sort.by("cid").descending()));
/*分页*/
Page<Customer> all1 = repository.findAll(PageRequest.of(0, 2,Sort.by("cid").descending()));
System.out.println(all.getTotalPages());//获取总页数
System.out.println(all.getTotalElements());//获取总数量
System.out.println(all.getContent());//获取当前页的所有数据
}
/**
* 排序
*/
@Test
public void testSort(){
Sort sort = Sort.by("custId").descending();
Iterable<Customer> all = repository.findAll(sort);
System.out.println(all);
}
/**
* 类型安全排序方式
*/
@Test
public void testSortTypeSafe(){
Sort.TypedSort<Customer> sortType = Sort.sort(Customer.class);
Sort sort = sortType.by(Customer::getCustId).descending();
Iterable<Customer> all = repository.findAll(sort);
System.out.println(all);
}
}