【发布时间】:2016-02-15 15:01:35
【问题描述】:
我正在尝试一个简单的问答应用程序,它包含三个类 Quiz、Question 和 Answer。基本关系如下:
@Entity
public class Quiz {
@Id
@GeneratedValue
private Long id;
private String description;
@OneToMany(cascade=CascadeType.PERSIST, fetch=FetchType.EAGER)
private List<Question> questions = new ArrayList<>();
@Entity
public class Question {
@Id
@GeneratedValue
private Long id;
private String description;
@ElementCollection(fetch=FetchType.EAGER)
private List<Answer> answers;
@Embeddable
public class Answer {
private String description;
private boolean correct;
JPA/数据库已正确加载,其中包含一个问题和三个答案的单个测验。但是,返回的相应 JSON 有很多重复数据。
{
"id" : 1,
"description" : "Intro to Spring 4",
"questions" : [ {
"id" : 1,
"description" : "What is Spring?",
"answers" : [ {
"description" : "A season",
"correct" : false
}, {
"description" : "A coily wire",
"correct" : false
}, {
"description" : "A wonderful framework",
"correct" : true
} ]
}, {
"id" : 1,
"description" : "What is Spring?",
"answers" : [ {
"description" : "A season",
"correct" : false
}, {
"description" : "A coily wire",
"correct" : false
}, {
"description" : "A wonderful framework",
"correct" : true
} ]
}, {
"id" : 1,
"description" : "What is Spring?",
"answers" : [ {
"description" : "A season",
"correct" : false
}, {
"description" : "A coily wire",
"correct" : false
}, {
"description" : "A wonderful framework",
"correct" : true
} ]
} ]
}
有人看到明显的东西吗?我正在使用 Jackson 映射器。
【问题讨论】:
-
我感觉您的 JPA 执行 JOIN 导致 3 行的问题与您的 3 个答案相同...您可以分享用于输出该 JSON 的代码吗?
-
实际上,我使用的是 Spring CrudRepository,所以我唯一的代码是这个控制器方法 @RequestMapping("quizzes/{id}") public Quiz quiz(@PathVariable Long id){ return quizRepository.findOne( ID); }
标签: json spring rest duplicates