• Spring JPA 核心概念


    Spring JPA 核心概念

    翻译: Core concepts
    Spring数据存储库抽象中的中心接口是repository。它采用要管理的域类以及域类的ID类型作为类型参数。此接口主要充当标记接口,以捕获要使用的类型,并帮助您发现扩展此接口的接口。CrudRepository为被管理的实体类提供了复杂的CRUD功能。

    例3:CrudRepository 接口

    public interface CrudRepository<T, ID> extends Repository<T, ID> {
    
      <S extends T> S save(S entity);      //保存指定的实体
    
      Optional<T> findById(ID primaryKey); //返回给定id的实体
    
      Iterable<T> findAll();               //返回所有实体
    
      long count();                        //统计实体个数
    
      void delete(T entity);               //删除给定的实体
    
      boolean existsById(ID primaryKey);   //判断给定id的实体是否存在
    
      // … more functionality omitted.
    }
    

    我们还提供特定于持久性技术的抽象,例如JpaRepositoryMongoRepository。这些接口扩展了CrudRepository,在CrudRepository的通用接口外,还增加拓展了公开了其他基础持久性技术的接口功能。

    ​ 在CrudRepository之上,有一个PagingAndSortingRepository抽象接口,它添加了其他方法来简化对实体的分页访问:

    例4:PagingAndSortingRepository接口

    public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
    
      Iterable<T> findAll(Sort sort);
    
      Page<T> findAll(Pageable pageable);
    }
    

    ​ 获取页面大小为20的user实体列表第二页的代码如下所示:

    PagingAndSortingRepository<User, Long> repository = // … get access to a bean
    Page<User> users = repository.findAll(PageRequest.of(1, 20));
    

    注:Page从0开始

    ​ 除了查询方法之外,还可以使用计数和删除查询的查询派生。以下列表显示派生计数查询的接口定义:

    例5:计数查询派生

    interface UserRepository extends CrudRepository<User, Long> {
    
      long countByLastname(String lastname);
    }
    

    ​ 以下列表显示了派生的删除查询的接口定义:

    例6:删除查询派生

    interface UserRepository extends CrudRepository<User, Long> {
    
      long deleteByLastname(String lastname);
    
      List<User> removeByLastname(String lastname);
    }
    

    附注:SpringBoot 项目分页查询Demo

    Dao

    public interface ShipDao extends JpaRepository<ShipPO,Integer> {  
        Page<ShipPO> findByRegion(String region,Pageable pageable);  
    }
    

    Service

    @RequestMapping(value = "/ship",method = RequestMethod.GET)
        public List<ShipPO> GetShip( 
                @RequestParam(value = "region",required = false,defaultValue = "none") String region
        ){
                Pageable pageable = PageRequest.of(page,5, Sort.by(Sort.Direction.DESC,"sdate"));
                //无区域限制
                    //根据地区查询,有地区限制 无状态限制
                shiplist = shipDao.findByRegion(region,pageable).get().collect(Collectors.toList());
    
            return shiplist;
        }
    

    下一篇:【Spring JPA 查询】

  • 相关阅读:
    hdu 4465 概率称号
    Log4j配置文件位置+Spring数据源配置文件位置
    Centos 6.5下一个SNMP简单配置(snmp protocol v3,监控宝)
    过程 线 多线程 并发 同步异步
    django简单图表
    十年
    一起写2048(160行python代码)
    leetcode
    匹配算法重载方法
    串行卧重建10:小设计,而不是大布局
  • 原文地址:https://www.cnblogs.com/masterchd/p/13564249.html
Copyright © 2020-2023  润新知