Java 使用 jackson 将双向 JPA 实体序列化为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22615317/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Serialize bi-directional JPA entities to JSON with Hymanson
提问by mmjmanders
I'm using Hymanson to serialize my JPA model into JSON.
我正在使用 Hymanson 将我的 JPA 模型序列化为 JSON。
I have the following classes:
我有以下课程:
import com.fasterxml.Hymanson.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
}
and
和
import com.fasterxml.Hymanson.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
}
I'm using the POJO mapping to serialize from model to JSON. When I serialize a Parent object I get the following JSON:
我正在使用 POJO 映射将模型序列化为 JSON。当我序列化父对象时,我得到以下 JSON:
{
"id": 1,
"name": "John Doe",
"children": [
{
"id": 1,
"name": "child1"
},{
"id": 2,
"name": "child2"
}
]
}
But when I serialize a Child I get the following JSON:
但是当我序列化一个 Child 时,我得到以下 JSON:
{
"id": 1,
"name": "child1"
}
The reference to the parent is missing. Is there a way to solve this?
缺少对父项的引用。有没有办法解决这个问题?
采纳答案by GSP59
I think you have to chose between the @JsonIdentityInfo and the @JsonBackReference/@JsonManagedReference.
我认为您必须在@JsonIdentityInfo 和@JsonBackReference/@JsonManagedReference 之间进行选择。
I would go with : @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="id") on your entities, removes @JsonBackReference/@JsonManagedReference pairs.
我会使用:@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property="id") 在您的实体上,删除 @JsonBackReference/@JsonManagedReference 对。
And add @JsonIgnore on the fields you want to exclude.
并在要排除的字段上添加 @JsonIgnore。
回答by StaxMan
The problem is that use of managed/back references requires that direction of traversal is always from parent to child (that is, using managed reference first). This is a limitation for these annotations.
问题是使用托管/返回引用要求遍历方向始终是从父级到子级(即首先使用托管引用)。这是这些注释的限制。
As the other answer suggests, use of Object Ids is the more flexible alternative that could perhaps work.
正如另一个答案所暗示的那样,使用 Object Ids 是可能可行的更灵活的替代方案。
One other option that could perhaps work would be to use JSON Views or JSON Filter to conditionally include/exclude parent reference, if you can separate cases. This could get messy.
另一个可能可行的选择是使用 JSON 视图或 JSON 过滤器有条件地包含/排除父引用,如果您可以分开案例。这可能会变得混乱。
回答by Jorge
You can use JsonManagedReference / JsonBackReference and at the same time use JsonIdentityInfo to complement bidirectional relationships.
您可以使用 JsonManagedReference / JsonBackReference 同时使用 JsonIdentityInfo 来补充双向关系。
In question Class:
问题类:
// bi-directional one-to-many association to Answer (Question is owner)
@JsonManagedReference
@OneToMany(mappedBy = "question", cascade = CascadeType.ALL)
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@QuestionAnswers")
private Set<Answer> answers = new HashSet<>();
In answer Class: // bi-directional many-to-one association to Question
In answer Class: // 双向多对一关联到问题
@JsonBackReference
@ManyToOne
@JoinColumn(name = "questionId", referencedColumnName="id", foreignKey = @ForeignKey(name = "fk_answer_question"))
private Question question;
If you need parent reference in child object, remove Managed / Back Reference, this works fine for me.
如果您需要子对象中的父引用,请删除托管/反向引用,这对我来说很好用。
回答by liy
You can use @JsonBackReference/@JsonManagedReference and add this method to child
您可以使用 @JsonBackReference/@JsonManagedReference 并将此方法添加到 child
@JsonProperty
public Long getParentId() {
return parent == null ? null : parent.getId();
}
Result will be:
结果将是:
{
"id": 1,
"name": "child1",
"parentId": 1
}
I hope this helps someone.
我希望这可以帮助别人。
回答by Radovan
@JsonIgnoreProperties({"excludedPropertyName"})
can do the job.
@JsonIgnoreProperties({"excludedPropertyName"})
可以胜任。
@Entity
public class Parent {
@JsonIgnoreProperties({"parent"})
@OneToMany(mappedBy = "parent")
private List<Child> children;
// ...
}
@Entity
public class Child {
@JsonIgnoreProperties({"children"})
@ManyToOne
private Parent parent;
// ...
}