【发布时间】:2014-05-02 03:48:45
【问题描述】:
我正在使用 Jackson 将我的 JPA 模型序列化为 JSON。
我有以下课程:
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.Set;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class)
@Entity
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@JsonManagedReference
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Child> children;
//Getters and setters
}
和
import com.fasterxml.jackson.annotation.*;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class)
@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@JsonBackReference
@ManyToOne
@JoinColumn(name = "parentId")
private Parent parent;
//Getters and setters
}
我正在使用 POJO 映射从模型序列化到 JSON。当我序列化父对象时,我得到以下 JSON:
{
"id": 1,
"name": "John Doe",
"children": [
{
"id": 1,
"name": "child1"
},{
"id": 2,
"name": "child2"
}
]
}
但是当我序列化一个 Child 时,我得到以下 JSON:
{
"id": 1,
"name": "child1"
}
缺少对父级的引用。 有没有办法解决这个问题?
【问题讨论】:
-
在实体中包含与 UI 相关的逻辑(即 json 注释)不是很糟糕吗?这不是扼杀模块化吗?
-
嗯...不。这就是实体存在的主要原因:作为数据模型表示,无论是 JPA、XML、JSON 还是这些的组合。让您的整个应用程序使用一组实体是设计良好的应用程序的指标 - 一组实体会导致单点故障,这反过来使应用程序在更高程度上可维护(和可交换)。跨度>
标签: java json hibernate jpa jackson