Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

spring boot+mysql+jpa如何根据实际需求获取指定的字段,并返回json

数据库表里存的数据有三个字段,id,name和age。用默认的jpa,bean的情况下,查询的结果返回了所有字段组成的json对象。如果现在只想要name和age的json对象,该如处理?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你可以尝试使用@JsonView注解来解决:

@GetMapping("{id}")
@JsonView({Name.class, Age.class})
public Student findById(@PathVxxxx Long id) {
    return xxx;
}
class Student {
    private Long id;
    
    @JsonView(Name.class)
    private String name;
    
    @JsonView(Age.class)
    private Integer age;
}
interface Name {}
interface Age {}

此时,进行该方法的请求时,则仅返回name及age字段。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...