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:查询方法定义和使用规则

SpringDataJpa小结
SpringDataJpa小结

  • 对于这种方法名查询的弊端:
    • 方法名较长(约定大于配置)
    • 对于更复杂的查询则无法实现
  • 解决方式:@Query
@Query注解的使用(使用最多)
  • 在Respository的方法中使用,不需要遵循查询方法命名规则
  • 只需要将@Query定义在Respository中的方法上
  • 支持命名参数和索引参数的使用
    • 举例like的使用
      • 命名参数:
        @Query("select e from Employee e where e.name like %:name% ")
        public List<Employee> queryLike(@Param(“name”)String name);
      • 索引参数:
        @Query("select e from Employee e where e.name like %?1% ")
        public List<Employee> queryLike(String name);
  • 本地原生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)
    SpringDataJpa小结
JpaRepository使用
  • findAll
  • findAll(Sort sort)
  • save(entities)
  • flush
  • deleteInBatch(entities)
JpaSpecificationExecutor接口使用
  • JpaSpecificationExecutor封装了JPA Criteria查询条件
    SpringDataJpa小结

相关文章:

  • 2021-05-19
  • 2022-12-23
  • 2022-12-23
  • 2021-12-17
  • 2021-12-04
  • 2021-05-05
  • 2021-12-17
  • 2021-11-25
猜你喜欢
  • 2022-01-15
  • 2021-07-28
  • 2021-08-22
  • 2022-01-17
  • 2021-09-15
  • 2022-02-13
  • 2022-01-19
相关资源
相似解决方案