Sping Data 對JPA的支持


JPA中關系型數據庫的CRUD

在Spring中,將對持久層的訪問抽象為Repository,Spring data對jpa的支持中在對關系型數據庫的CRUD中有兩個重要的接口實現

CrudRepository<Entity,ID>

@author dengrixiong

public interface AddressEntityRepository extends CrudRepository<AddressEntity,String>{
    List<AddressEntity> findByStreetLike(String stree);
}
  • 在Spring支持中,如果JpaRepostorry沒有自己的實現的化,會在容器中注入SimpleJpaRepository的實現,這個對象實現了JpaRepository的接口,完成相關的CRUD。
  • 我們在看一下CrudRepository中定義了哪些方法,基本的增刪改查的方法都提供了支持
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package org.springframework.data.repository; import java.util.Optional; @NoRepositoryBean public interface CrudRepository<T, ID> extends Repository<T, ID> { <S extends T> S save(S var1); <S extends T> Iterable<S> saveAll(Iterable<S> var1); Optional<T> findById(ID var1); boolean existsById(ID var1); Iterable<T> findAll(); Iterable<T> findAllById(Iterable<ID> var1); long count(); void deleteById(ID var1); void delete(T var1); void deleteAll(Iterable<? extends T> var1); void deleteAll(); }

PadingAsndSortingRepository<Entity,ID>

PadingAndSortingRepository接口主要拓展了排序和分頁查詢的方法,我們具體看一下其中聲明了哪些方法

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.data.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

@NoRepositoryBean
public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
    Iterable<T> findAll(Sort var1);

    Page<T> findAll(Pageable var1);
}

從名字我們就可以看出,拓展了根據排序規則查詢的方法和分頁查詢的方法。具體的使用規則,有如下兩步

  • 定義自己的實體repository從PadingAndSortingRepository中繼承
  • 創建Pageable對象
package com.wanda.cloud.jpa.spring.page;

import com.wanda.clound.mydata.common.entity.AddressEntity;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface AddressEntityRepository extends PagingAndSortingRepository<AddressEntity,String> {

}
@Test
    public void testfindAllByPage(){
        Pageable pageable=PageRequest.of(1,1);
        Page<AddressEntity> result= addressEntityRepository.findAll(pageable);
        result.forEach(addressEntity -> {
           System.out.println(addressEntity.getId()+"\\"+addressEntity.getCity()+"\\"+ addressEntity.getStreet());
       });

    }

其中 PageRequest是PageAble的實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM