我有一个简单的问答应用程序,我正在试验,它有三个类别的测验,问题和答案。基本关系如下:
@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 mapper。
发布于 2018-09-11 02:56:54
在getter方法中注入@JsonProperty("yourFiledName")对我来说很有效。
@Entity
public class Quiz {
@Id
@GeneratedValue
private Long id;
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@JsonProperty("description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**对问题实体类执行相同的操作**/
注:@JsonPropertiy来自Jackson库。对于maven用户,下面是依赖项
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
发布于 2019-01-30 00:08:40
只为那些在这个问题上苦苦挣扎的人。只需将@ElementCollection(fetch=FetchType.EAGER)
设置为@ElementCollection(fetch=FetchType.LAZY)
这解决了我的问题!
https://stackoverflow.com/questions/35412605
复制相似问题