interface Repository:
是SpringData的核心接口,不提供任何方法
- 是一个空接口(标记接口)
- 如果我们的接口extends Respository,那么我们的接口会被Spring容器管理
- 不想extends Respository的话就用注解:@RespositoryDefinition(domainClass=xxx.class,idClass=xxx.class)标记接口
- 子接口:
- CrudRepository:继承了Repository,实现了CRUD相关方法
- PagingAndSortingRepository:继承了CrudRepository,实现了分页排序的相关方法
- JpaRepository:继承了PagingAndSortingRepository,实现了JPA规范的相关方法
是一个public interface Respository<T,ID extends Serializable>{}
可以不去extends Repository 而使用@RespositoryDefinition注解
Repository:查询方法定义和使用规则
- 对于这种方法名查询的弊端:
- 方法名较长(约定大于配置)
- 对于更复杂的查询则无法实现
- 解决方式:@Query
@Query注解的使用(使用最多)
- 在Respository的方法中使用,不需要遵循查询方法命名规则
- 只需要将@Query定义在Respository中的方法上
- 支持命名参数和索引参数的使用
- 本地原生sql查询:
@Query(nativeQuery=true,value=“select count(1) from employee”)
public int getCount();
更新删除及事务操作
-
@Modifying注解使用
-
@Modifying结合@Query注解执行更新操作
@Modifying
@Query(“update Employee e set e.age= :age where e.id= :id”)
public void update (@Param(“id”)Integer id,@Param(“age”)Integer age); -
@Transactional在SpringData中的使用
- 事务一般用于service层
CrudRepository接口
自己的dao层接口继承CrudRepository<T,ID>
PagingAndSortingRepository接口
自己的dao层接口继承PagingAndSortingRepository<T,ID>
- 该接口包含分页和排序的功能
- 带排序的查询findAll(Sort sort)
- 带排序的分页查询findAll(Pageable pageable)
JpaRepository使用
- findAll
- findAll(Sort sort)
- save(entities)
- flush
- deleteInBatch(entities)
JpaSpecificationExecutor接口使用
- JpaSpecificationExecutor封装了JPA Criteria查询条件