spring data jpa 接口

主要来看看Spring Data JPA提供的接口,也是Spring Data JPA的核心概念:
1:Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别。

                   https://blog.csdn.net/u014268482/article/details/81014104

                    https://blog.csdn.net/fly910905/article/details/78557110

        直接在接口中定义查询方法,如果是符合规范的,可以不用写实现,目前支持的关键字写法如下:

驼峰起名的命名法:

spring data jpa 接口

 也可以用@Query来查询和更新,不过它更多的是用来查询。

https://www.cnblogs.com/zj0208/p/6008627.html

1. 一个使用@Query注解的简单例子

@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
List<Book> findByPriceRange(long price1, long price2);

 

2.  Like表达式

@Query(value = "select name,author,price from Book b where b.name like %:name%")
List<Book> findByNameMatch(@Param("name") String name);

 

3. 使用Native SQL Query

所谓本地查询,就是使用原生的sql语句(根据数据库的不同,在sql的语法或结构方面可能有所区别)进行查询数据库的操作。

@Query(value = "select * from book b where b.name=?1", nativeQuery = true)
List<Book> findByName(String name);


2:CrudRepository :是Repository的子接口,提供CRUD的功能

     https://blog.csdn.net/strive_peter/article/details/76276758

  • CrudRepository 接口提供了最基本的对实体类的添删改查操作 

  • T save(T entity);//保存单个实体 

  • Iterable<T> save(Iterable<? extends T> entities);//保存集合       

  • T findOne(ID id);//根据id查找实体        

  • boolean exists(ID id);//根据id判断实体是否存在        

  • Iterable<T> findAll();//查询所有实体,不用或慎用!        

  • long count();//查询实体数量        

  • void delete(ID id);//根据Id删除实体        

  • void delete(T entity);//删除一个实体 

  • void delete(Iterable<? extends T> entities);//删除一个实体的集合        

  • void deleteAll();//删除所有实体,不用或慎用! 

3:PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能

https://blog.csdn.net/zgf19930504/article/details/50537225

 

  1. Iterable<T> findAll(Sort sort); //查询所有,排序,不进行分页

  2. Page<T> findAll(Pageable pageable);


4:JpaRepository:是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等。

             对PagingAndSortingRepository进行了适配,就是不报错了。类型自动匹配。
5:JpaSpecificationExecutor:用来做负责查询的接口

public interface JpaSpecificationExecutor<T> {

    T findOne(Specification<T> spec);

    List<T> findAll(Specification<T> spec);

    Page<T> findAll(Specification<T> spec, Pageable pageable);

    List<T> findAll(Specification<T> spec, Sort sort);

    long count(Specification<T> spec);
}

https://blog.csdn.net/u012843873/article/details/52449105

6:Specification:是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可。