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