Spring Data JPA学习笔记(一)

JPA基础查询方法

1、整体认识

Spring Data是一个基于Spring 的数据访问编程模型。Spring Data Common是Spring Data所有模块的公共部分。

Spring Data的主要子项目有:Spring Data Common、Spring Data Gemfire、Spring Data JPA、Spring Data KeyValue等10个。社区支持子项目有8个,其他子项目3个。

2、Spring Data JPA主要类及结构图

Spring Data JPA的7个接口:Repository、CrudRepository、PagingAndSortingRepository、QueryByExampleExecutor、JpaRepository、JpaSpecificationExecutor、QueryDslPredicateExecutor。

Spring Data JPA两个实现类:SimpleJpaRepository、QueryDslJpaRepository。

JPA底层封装类:EntityManager、EntityManagerImpl。

结构图如下:

3、JPA的基础查询方法

1)Repository为Spring Data中最底层的接口、最顶级的父类。这个接口定义了所有Repository操作的实体和ID两个泛型参数。

源码如下:

public interface Repository<T, ID extends Serializable>{
}

只要继承该接口,就能使用Spring JPA的很多约定方法查询和注解查询。

2)CrudRepository

package org.springframework.data.repository;
import java.io.Serializable;

@NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {

	<S extends T> S save(S entity);
	<S extends T> Iterable<S> save(Iterable<S> entities);
	T findOne(ID id);
	boolean exists(ID id);
	Iterable<T> findAll();
	Iterable<T> findAll(Iterable<ID> ids);
	long count();
	void delete(ID id);
	void delete(T entity);
	void delete(Iterable<? extends T> entities);
	void deleteAll();
}

保存/更新实体:SimpleJpaRepository的实现方法,先判断是否存在,再判断是新增还是更新。

删除实体:SimpleJpaRepository的实现方法,先查询是否存在,再进行删除。

3)PagingAndSortingRepository

继承了CrudRepository的所有基本方法,增加了分页、排序等对结果进行限制的、基本的、常用的分页方法。

使用示例:

//排序并分页
@GetMapping(path = "/page")
@ResponseBody
public Page<User> getAllUserByPage(){
    return userPagingAndSortingRepository.findAll(new PageRequest(1, 20, new Sort(new Sort.Order(Sort.Direction.ASC, "name"))));
}

//排序查询
@GetMapping(path = "/sort")
@ResponseBody
public Page<User> getAllUserWithSort(){
    return userPagingAndSortingRepository.findAll(new Sort(new Sort(new Sort.Order(Sort.Direction.ASC, "name"))));
}

以上三个类是为兼容NoSQL进行的一些抽象封装,JpaRepository是对关系型数据库进行封装。

4)JpaRepository

它与CrudRepository比较,增加支持了QueryByExample,批量删除,默认将查询结果变为List。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值