使用查询的时候可以使用value注解,也是一种视图查询
1. 在类上面使用Lombok的value注解
@Value
public class NameEntity {
String name;
Long id;
}
添加对应查询方法
<T> List<T> findByAgeGreaterThan(int age, Class<T> type);
测试方法
@ApiOperation(value = "find", httpMethod = "GET")
@GetMapping("/find")
public List<NamesOnly> find(@RequestParam int age) {
return catRepository.findByAge(age);
}
2. 在接口类上面使用org.springframework.beans.factory.annotation.Value的value注解
public interface NamesOnly {
String getName();
@Value("#{target.name + ' ' + target.id}")
String getFullName();
@Value("#{@valueUtils.getName(target)}")
String getValue();
}
添加对应查询方法
List<NamesOnly> findByAge(int age);
3. 使用泛型将返回类传入查询方法
<T> List<T> findByAgeGreaterThan(int age, Class<T> type);
<T> List<T> findBy(Class<T> type);
<T> Page<T> findBy(Pageable pageable, Class<T> type);
添加对应的查询方法
@ApiOperation(value = "findType", httpMethod = "GET")
@GetMapping("/find/type")
public List<NamesOnly> findType() {
return catRepository.findBy(NamesOnly.class);
}
@ApiOperation(value = "findType2", httpMethod = "GET")
@GetMapping("/find/type2")
public List<NameEntity> findType2() {
return catRepository.findBy(NameEntity.class);
}
@ApiOperation(value = "findTypeAge", httpMethod = "GET")
@GetMapping("/find/type/age")
public List<NamesOnly> findTypeAge(@RequestParam int age) {
return catRepository.findByAgeGreaterThan(age, NamesOnly.class);
}
@ApiOperation(value = "findTypeAge2", httpMethod = "GET")
@GetMapping("/find/type/age2")
public List<NameEntity> findTypeAge2(@RequestParam int age) {
return catRepository.findByAgeGreaterThan(age, NameEntity.class);
}
@ApiOperation(value = "findTypePage", httpMethod = "GET")
@GetMapping("/find/type/page")
public Page<NamesOnly> findTypePage(@RequestParam int pageSize, @RequestParam int pageNum) {
Pageable pageable = PageRequest.of(pageNum, pageSize);
return catRepository.findBy(pageable, NamesOnly.class);
}
@ApiOperation(value = "findTypePage2", httpMethod = "GET")
@GetMapping("/find/type/page2")
public Page<NameEntity> findTypePage2(@RequestParam int pageSize, @RequestParam int pageNum) {
Pageable pageable = PageRequest.of(pageNum, pageSize);
return catRepository.findBy(pageable, NameEntity.class);
}
源码参考 GITHUB
欢迎关注微信交流