查询满足某个范围的值。比如下面的方法就实现查询满足某个年龄范围的人员的信息。
- @Query(value = "select new github.snailclimb.jpademo.model.dto.UserDTO(p.name,p.age,c.companyName,s.name) " +
- "from Person p left join Company c on p.companyId=c.id " +
- "left join School s on p.schoolId=s.id " +
- "where p.age between :small and :big")
- List<UserDTO> filterUserInfoByAge(int small,int big);
实际使用:
List userDTOS = personRepository.filterUserInfoByAge(19,20);
5.测试类和源代码地址
- @SpringBootTest
- @RunWith(SpringRunner.class)
- public class PersonRepositoryTest2 {
- @Autowired
- private PersonRepository personRepository;
-
- @Sql(scripts = {"classpath:/init.sql"})
- @Test
- public void find_person_age_older_than_18() {
- List<Person> personList = personRepository.findByAgeGreaterThan(18);
- assertEquals(1, personList.size());
- }
-
- @Sql(scripts = {"classpath:/init.sql"})
- @Test
- public void should_get_user_info() {
- Optional<UserDTO> userInformation = personRepository.getUserInformation(1L);
- System.out.println(userInformation.get().toString());
- }
-
- @Sql(scripts = {"classpath:/init.sql"})
- @Test
- public void should_get_user_info_list() {
- PageRequest pageRequest = PageRequest.of(0, 3, Sort.Direction.DESC, "age");
- Page<UserDTO> userInformationList = personRepository.getUserInformationList(pageRequest);
- //查询结果总数
- System.out.println(userInformationList.getTotalElements());// 6
- //按照当前分页大小,总页数
- System.out.println(userInformationList.getTotalPages());// 2
- System.out.println(userInformationList.getContent());
- }
-
- @Sql(scripts = {"classpath:/init.sql"})
- @Test
- public void should_filter_user_info() {
- List<String> personList=new ArrayList<>(Arrays.asList("person1","person2"));
- List<UserDTO> userDTOS = personRepository.filterUserInfo(personList);
- System.out.println(userDTOS);
- }
-
- @Sql(scripts = {"classpath:/init.sql"})
- @Test
- public void should_filter_user_info_by_age() {
- List<UserDTO> userDTOS = personRepository.filterUserInfoByAge(19,20);
- System.out.println(userDTOS);
- }
- }
六 总结
本节我们主要学习了下面几个知识点:
自定义 SQL 语句实现连表查询;
自定义 SQL 语句连表查询并实现分页操作;
条件查询:IN 查询,BETWEEN查询。
(编辑:ASP站长网)
|