Learning repository --- 05, spring-data-commons in the Spring-Data-Jpa (six)

1, spring-data-commons project

  spring-data-commons project is the core of all spring-data project, we look at the repository packages under the project interfaces and annotations.

    

 

 2, Repository interfaces and @RepositoryDefinition comment

  Among the most important is the interface to the Repository. It is to do database operations of the bottom of the abstract interface, top parent, look at its source code open Repository interfaces, and discovered that in fact what methods are not only play a role identity. Capture id type field type and field class to manage. Purpose is to preserve the type of information, and can find the interface inherit the interface, to help us create a proxy class during class path scan.

@Indexed
public interface Repository<T, ID> {

}

  @Indexed We found a @Indexed comment on the Repository interface is a comment Spring5 provide for improved application launch performance. The presence of the annotation does not work alone, in order to take effect, then, to add a spring-context-indexer dependence. @CompoentScan will scan the specified package to be generated at compile time bean write METE-INF / spring.components file, when the project started, it will read the file and will not scan a specified package, so as to enhance performance.

  As long as we inherit Repository interfaces, and according to its rules to name the interface methods, database operations can be carried out. (Repository interfaces and inheritance equal value is added @RepositoryDefinition notes on the interface)

Example:

/ ** 
* Books persistence
* @author caofanqi
* @RepositoryDefinition annotations using the Repository succession has the same effect
* /
// @ RepositoryDefinition (= domainClass a Book.class, IdClass = Long.class)
public interface BookRepository the extends Repository <Book, Long> {

/ **
* the title for books
* @param bookName book name
* @return book listing the book name
* /
list <book> findBooksByBookNameContains (String bookName);

}
@Transactional
@Rollback(false) @SpringBootTest
class BookRepositoryTest { @Resource private BookRepository bookRepository; @Test void findBooksByBookNameContains() { System.out.println("bookRepository : " + bookRepository.getClass().getName()); List<Book> books = bookRepository.findBooksByBookNameContains("Java"); System.out.println(books); } }

  This will according to our argument passed to the query like qualified books, generated sql statement is as follows:

     

 

 

 

 

3, CrudRepository interfaces comment @NoRepositoryBean

  CrudRepository Interface Repository is a sub-interface, provides a common CRUD methods. @NoRepositoryBean annotation on the interface mean, let Spring generate this kind of proxy class.

Spring @NoRepositoryBean // let generate the proxy class this only provides a common set of CRUD methods.
public  interface CrudRepository <T, ID> the extends the Repository <T, ID> {

    / ** 
   * Save method * / 
    <S the extends T> S Save (S Entity);

    /**
   * 保存*/
    <S extends T> Iterable<S> saveAll(Iterable<S> entities);

    /**
     * 根据id进行查询*/
    Optional<T> findById(ID id);

    /**
     * 判断给定id的数据是否存在*/
    boolean existsById(ID id);

    /**
     * 查询全部,数据量很大的时候,谨慎使用*/
    Iterable<T> findAll();

    /**
     * 根据给定ids查询符合条件的数据
     */
    Iterable<T> findAllById(Iterable<ID> ids);

    /**
     * 统计条数*/
    long count();

    /**
     * 根据id删除*/
    void deleteById(ID id);

    /**
     * 删除给定实体*/
    void delete(T entity);

    /**
     * 删除给定实体*/
    void deleteAll(Iterable<? extends T> entities);

    /**
     * 删除全部
     */
    void deleteAll();
}

  我们要想使用这些方法,只需自己的Repository继承该接口即可。

4、PagingAndSortingRepository接口

  是CrudRepository的子接口,也不会生成代理,只是提供分页和排序的方法。

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

    /**
     * 根据sort去所有对象排序的集合*/
    Iterable<T> findAll(Sort sort);

    /**
     * 根据pageable进行分页,pageable中可以包含sort*/
    Page<T> findAll(Pageable pageable);
}

  分页相关对象:

  Sort查询的排序选项,至少提供一个属性列表来进行排序,不能是null或空,默认是升序ASC;
  可以通过Sort.by 来构建Sort对象:
    public static Sort by(String... properties) 根据给定的属性列表进行升序排序;
    public static Sort by(Direction direction, String... properties) 指定属性和排序方向,Direction.ASC(升序)、Direction.DESC(降序);
    public static Sort by(Order... orders)/public static Sort by(List<Order> orders) 根据给定的一组order进行排序。

  Order,实现一个排序对,提供方向和属性,为sort提供输入。也就是说,可以针对每一个属性设置不同的升序或降序。
  可以通过一下方式来构建Order对象:
    public static Order by(String property) ,指定属性返回order对象,默认使用升序。
    public static Order asc(String property),返回指定属性升序的order对象。
    public static Order desc(String property),返回指定属性降序的order对象。

  Pageable分页信息的抽象接口,实现类是PageRequest;
  可以通过一下方式来构建Pageable对象:
    public static PageRequest of(int page, int size),创建一个未排序的PageRequest,page从0开始;
    public static PageRequest of(int page, int size, Direction direction, String... properties),创建一个根据给定方向和属性排序的分页对象。
    public static PageRequest of(int page, int size, Sort sort),创建一个根据sort进行排序的分页对象。

  Page,封装分页结果信息,可以通过如下方法获取分页信息。
    page.getContent() ,分页查询结果列表;
    page.getNumberOfElements(),当前分页结果列表中的元素个数;
    page.getTotalElements(),当前条件下总条数;
    page.getTotalPages(),总页数;
    page.getNumber(),我们自己传的page;
    page.getSize(),我们自己传入的size。

 代码示例:

    @Test
    void testPagingAndSortingRepository(){

        Sort.Order id = Sort.Order.by("id");
        Sort.Order bookName = Sort.Order.desc("bookName");
        Sort sort = Sort.by(id,bookName);

        Pageable pageable = PageRequest.of(2,2, sort);

        Page<Book> page = bookRepository.findAll(pageable);

        System.out.println("分页查询结果列表:" + page.getContent());
        System.out.println("当前分页结果列表中的元素个数:" + page.getNumberOfElements());
        System.out.println("当前条件下总条数:" + page.getTotalElements());
        System.out.println("总页数:" +page.getTotalPages());
        System.out.println("我们自己传的page:" +page.getNumber());
        System.out.println("我们自己传入的size:" +page.getSize());

        
    }

 

源码地址:https://github.com/caofanqi/study-spring-data-jpa

 



 

Guess you like

Origin www.cnblogs.com/caofanqi/p/11831362.html