【发布时间】:2018-03-22 21:08:04
【问题描述】:
我正在使用 Spring 框架、Hibernate 和 JSON 开发 REST Web 应用程序。请假设我有两个如下实体:
BaseEntity.java
@MappedSuperclass
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "id" )
public abstract class BaseEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
public long getId() {
return id;
}
}
大学.java
public class University extends BaseEntity {
private String uniName;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER,orphanRemoval = true)
@JoinColumn(name = "university_id")
private List<Student> students=new ArrayList<>();
// setter an getter
}
学生.java
public class Student extends BaseEntity{
private String stuName;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "university_id",updatable = false,insertable = false)
private University university;
// setter an getter
}
当我调用我的 rest api 来列出大学时,一切都按我的预期正常工作,但是当我调用我的 rest api 来热切地列出学生时,我的 JSON 响应是
[
{
"id": 1,
"stuName": "st1",
"university": {
"id": 1,
"uniName": "uni1"
}
},
{
"id": 2,
"stuName": "st2",
"university": 1
}
]
但我的期望回应是:
[
{
"id": 1,
"stutName": "st1",
"university":
{
"id": 1,
"uniName": "uni1"
}
},
{
"id": 2,
"stutName": "st2",
"university":
{
"id": 1,
"uniName": "uni1"
}
}
更新 1:我的休眠注释工作正常我有 JSON 问题
要求:
双方都急需取货(大学这边可以)
我需要每个学生在学生方面的大学对象(当我急切地获取学生时)
我需要什么样的序列化或 JSON 配置来匹配我想要的响应?
更新 2:
通过删除 @JsonIdentityInfo 并编辑学生端,如下所示:
@ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "university_id",updatable = false,insertable = false) @JsonIgnoreProperties(value = "students", allowSetters = true) private University university;
json 响应还是一样的 我需要上面提到的期望回复。
谢谢
【问题讨论】:
-
添加
@JsonIgnore并尝试 -
@Hema 我需要在学生端有大学对象而不是大学ID
-
是的,我提供了相同的代码。你将在 Student 上大学
-
@Generic 不要以为可以用简单的通用方式来完成。你认为
list University is Ok因为那里没有重复项。@JsonIdentityInfoID/reference 机制的工作原理是,一个对象实例只被完全序列化一次,并由它的 ID 在其他地方引用 github.com/FasterXML/jackson-databind/issues/372
标签: java json spring hibernate jackson