加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

一文搞懂如何在Spring Boot正确中使用JPA

发布时间:2019-10-18 21:06:17 所属栏目:建站 来源:SnailClimb
导读:JPA 这部门内容上手很轻易,可是涉及到的对象照旧挺多的,网上大部门关于 JPA 的资料都不是出格一切,大部门用的版本也是较量落伍的。其它,我下面讲到了的内容也不行能涵盖全部 JPA 相干内容,我只是把本身认为较量重要的常识点总结在了下面。许多处所我

起首我们必要建设一个包括我们必要的 Person 信息的 DTO 工具,我们简朴第将其定名为 UserDTO,用于生涯和传输我们想要的信息。

  1. @Data 
  2. @NoArgsConstructor 
  3. @Builder(toBuilder = true) 
  4. @AllArgsConstructor 
  5. public class UserDTO { 
  6.     private String name; 
  7.     private int age; 
  8.     private String companyName; 
  9.     private String schoolName; 

下面我们就来写一个要领查询出 Person 的根基信息。

  1. /** 
  2.    * 连表查询 
  3.    */ 
  4.   @Query(value = "select new github.snailclimb.jpademo.model.dto.UserDTO(p.name,p.age,c.companyName,s.name) " + 
  5.           "from Person p left join Company c on  p.companyId=c.id " + 
  6.           "left join School s on p.schoolId=s.id " + 
  7.           "where p.id=:personId") 
  8.   Optional<UserDTO> getUserInformation(@Param("personId") Long personId); 

可以看出上面的 sql 语句和我们平常写的没啥区别,不同较量大的就是内里有一个 new 工具的操纵。

3.自界说 SQL 语句连表查询并实现分页操纵

若是我们要查询当前全部的职员信息并实现分页的话,你可以凭证下面这种方法来做。可以看到,为了实现分页,我们在@Query注解中还添加了 countQuery 属性。

  1. @Query(value = "select new github.snailclimb.jpademo.model.dto.UserDTO(p.name,p.age,c.companyName,s.name) " + 
  2.         "from Person p left join Company c on  p.companyId=c.id " + 
  3.         "left join School s on p.schoolId=s.id ", 
  4.         countQuery = "select count(p.id) " + 
  5.                 "from Person p left join Company c on  p.companyId=c.id " + 
  6.                 "left join School s on p.schoolId=s.id ") 
  7. Page<UserDTO> getUserInformationList(Pageable pageable); 

现实行使:

  1. //分页选项 
  2. PageRequest pageRequest = PageRequest.of(0, 3, Sort.Direction.DESC, "age"); 
  3. Page<UserDTO> userInformationList = personRepository.getUserInformationList(pageRequest); 
  4. //查询功效总数 
  5. System.out.println(userInformationList.getTotalElements());// 6 
  6. //凭证当前分页巨细,总页数 
  7. System.out.println(userInformationList.getTotalPages());// 2 
  8. System.out.println(userInformationList.getContent()); 

4.加餐:自定以SQL语句的其他用法

下面我只先容两种较量常用的:

IN 查询

BETWEEN 查询

虽然,尚有许多用法必要各人本身去实践了。

4.1 IN 查询

在 sql 语句中插手我们必要筛选出切合几个前提中的一个的环境下,可以行使 IN 查询,对应到 JPA 中也很是简朴。好比下面的要领就实现了,按照名字过滤必要的职员信息。

  1. @Query(value = "select new github.snailclimb.jpademo.model.dto.UserDTO(p.name,p.age,c.companyName,s.name) " + 
  2.         "from Person p left join Company c on  p.companyId=c.id " + 
  3.         "left join School s on p.schoolId=s.id " + 
  4.         "where p.name IN :peopleList") 
  5. List<UserDTO> filterUserInfo(List peopleList); 

现实行使:

List personList=new ArrayList<>(Arrays.asList("person1","person2"));List userDTOS = personRepository.filterUserInfo(personList);

4.2 BETWEEN 查询

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读