Spring data jpa 的基本使用

479 阅读3分钟

什么是SpringData

spring data概览

SpringData JPA只是SpringData中的一个子模块。JPA是一套标准接口,而Hibernate是JPA的实现 SpringData JPA 底层默认实现是使用Hibernate

SpringDataJPA的首个接口就是Repository,它是一个标记接口。只要我们的接口实现这个接口,那么我们就相当于在使用SpringDataJPA了。 只要我们实现了这个接口,我们就可以使用"按照方法命名规则"来进行查询。

解决:减少我们对数据访问层的开发量

Spring Data应用场景

  • SpringData提供一致的,大家都熟悉的编程模型,为了简化数据库的访问。

  • Spring Date JPA 目的:减少数据层的开发量

  • Spring Date Mongo DB:基于分布式数据层的数据库,在大数据层用的比较多

  • Spring Date Redis:开源,由C语言编写的,支持网络、内存,而且可以持久化的,提供非常多的语言支持

  • Spring Date Solr:高性能 搜索功能 对查询性能优化

搭建环境配置:

【spring data jpa】

1)依赖

org.springframework.data/spring-data-jpa

org.hibernate/hibernate-entitymanager

2)xml5个配置

a、配置数据源-dataSource

b、配置EntityManagerFactory class="org.springframework.ormljpa.LocalContainerEntityManagerFactoryBean"

c、配置事务管理器 class="org.springframework.orm.jpa.JpaTransactionManager"

d、配置支持注解的事务

e、配置spring data <jpa:repositories />

<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>1.8.1.RELEASE</version>
</dependency>

Repository

Repository接口讲解

 public interface Repository<T, ID extends Serializable>{
     
 }
  • Repository是一个空接口,标记接口;没有包含方法声明的接口
  • 如果我们定义的接口EmployeeRepository extends Repository,如果我们自己的接口没有extends Repository extends Repository运行时报错
  • 添加注解能到达不用extends Respository的功能
@RepositoryDefinition(domainClass = Employee.class,idClass = Integer.class)
  • Repostitory接口是Spring Data的核心接口,不能提供任何方法
  • public interface Repository<T,ID extends Serializable>
  • @RepositoryDefinition注解的使用

没有继承此接口,没纳入spring管理

Repository的子类及实现类:

分页

事务在Spring data中的使用:

  • 事务一般是在Service层
  • @Query、@Modifying、@Transaction的综合使用

把事务添加到dao层没有意义,一个service中可能有多个Dao的调用

复杂查询

在实际的开发中我们需要用到分页、删选、连表等查询的时候就需要特殊的方法或者自定义SQL

分页查询

分页查询在实际使用中非常普遍了,spring data jpa已经帮我们实现了分页的功能,在查询的方法中,需要传入参数Pageable ,当查询中有多个参数的时候Pageable建议做为最后一个参数传入

Page<User> findALL(Pageable pageable);
    
Page<User> findByUserName(String userName,Pageable pageable);

Pageable 是spring封装的分页实现类,使用的时候需要传入页数、每页条数和排序规则

Root可以理解为根对象,从根对象可以获取哪些内容呢 获取路径 构建条件

  • root:就是我们要查询的类型(Employee)
  • query:添加查询条件
  • cb:构建Predicate

小结:

  • 基本的增删改查和调用存储过程通过Spring Data JPA Repository来解决
  • 稍微复杂的查询或是批量操作使用QueryDSL或Spring Data Specification的API来解决
  • 特别特别复杂的查询操作可以使用Spring Data JPA Repository的注解定义native sql来解决

参考资料: