暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

SpringDataJPA笔记(6)-value注解的使用

生活不止眼前的代码 2019-05-10
265

网页浏览地址

https://blog.csdn.net/yingziisme/article/details/89819290


使用查询的时候可以使用value注解,也是一种视图查询

1. 在类上面使用Lombok的value注解

  1. @Value

  2. public class NameEntity {

  3. String name;

  4. Long id;

  5. }

添加对应查询方法

  1. <T> List<T> findByAgeGreaterThan(int age, Class<T> type);

测试方法

  1. @ApiOperation(value = "find", httpMethod = "GET")

  2. @GetMapping("/find")

  3. public List<NamesOnly> find(@RequestParam int age) {

  4. return catRepository.findByAge(age);

  5. }

2. 在接口类上面使用org.springframework.beans.factory.annotation.Value的value注解

  1. public interface NamesOnly {

  2. String getName();


  3. @Value("#{target.name + ' ' + target.id}")

  4. String getFullName();


  5. @Value("#{@valueUtils.getName(target)}")

  6. String getValue();

  7. }

添加对应查询方法

  1. List<NamesOnly> findByAge(int age);

3. 使用泛型将返回类传入查询方法

  1. <T> List<T> findByAgeGreaterThan(int age, Class<T> type);


  2. <T> List<T> findBy(Class<T> type);


  3. <T> Page<T> findBy(Pageable pageable, Class<T> type);

添加对应的查询方法

  1. @ApiOperation(value = "findType", httpMethod = "GET")

  2. @GetMapping("/find/type")

  3. public List<NamesOnly> findType() {

  4. return catRepository.findBy(NamesOnly.class);

  5. }


  6. @ApiOperation(value = "findType2", httpMethod = "GET")

  7. @GetMapping("/find/type2")

  8. public List<NameEntity> findType2() {

  9. return catRepository.findBy(NameEntity.class);

  10. }


  11. @ApiOperation(value = "findTypeAge", httpMethod = "GET")

  12. @GetMapping("/find/type/age")

  13. public List<NamesOnly> findTypeAge(@RequestParam int age) {

  14. return catRepository.findByAgeGreaterThan(age, NamesOnly.class);

  15. }


  16. @ApiOperation(value = "findTypeAge2", httpMethod = "GET")

  17. @GetMapping("/find/type/age2")

  18. public List<NameEntity> findTypeAge2(@RequestParam int age) {

  19. return catRepository.findByAgeGreaterThan(age, NameEntity.class);

  20. }


  21. @ApiOperation(value = "findTypePage", httpMethod = "GET")

  22. @GetMapping("/find/type/page")

  23. public Page<NamesOnly> findTypePage(@RequestParam int pageSize, @RequestParam int pageNum) {

  24. Pageable pageable = PageRequest.of(pageNum, pageSize);

  25. return catRepository.findBy(pageable, NamesOnly.class);

  26. }


  27. @ApiOperation(value = "findTypePage2", httpMethod = "GET")

  28. @GetMapping("/find/type/page2")

  29. public Page<NameEntity> findTypePage2(@RequestParam int pageSize, @RequestParam int pageNum) {

  30. Pageable pageable = PageRequest.of(pageNum, pageSize);

  31. return catRepository.findBy(pageable, NameEntity.class);

  32. }

源码参考 https://github.com/yingziisme/spring-boot-jpa-demo


文章转载自生活不止眼前的代码,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论