我有一个带自引用的Hibernate实体
@Entity
@Table(name = "category")
@NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 255)
private String name;
@Column(length = 255)
private String description;
@Column(nullable = false, length = 25, columnDefinition = "enum('Category','SubCategory','Indicator')")
private String type;
@ManyToMany
@JoinTable(name = "CategoryHierarchy", joinColumns = @JoinColumn(name = "parentId", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "childId", referencedColumnName = "id"))
private List<Category> childs;
// getters and setters
}
因此,当我获得所有实体时,显然我在反序列化JSON时面临无限递归。所以我添加了
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
在班级名称之上。 但现在,JSON只包含id或数字,如
{
"success": true,
"messages": [
{
"@id": 1,
"id": 5,
"name": "TestParentCategory ",
"description": "This is test Parent category",
"type": "Category",
"status": "New",
"childs": [
{
"@id": 2,
"id": 6,
"name": "TestChildCategory",
"description": "This is test child category",
"editTime": "2016-03-23T11:40:19",
"editedBy": null,
"createTime": "2016-03-23T11:40:19",
"createdBy": 10,
"type": "SubCategory",
"status": "New",
"childs": [
{
"@id": 3,
"id": 8,
"name": "TestChildCategory",
"description": "This is test child category",
"editTime": "2016-03-23T11:40:20",
"editedBy": null,
"createTime": "2016-03-23T11:40:20",
"createdBy": 10,
"type": "Indicator",
"status": "New",
"childs": [],
"parents": [
2,
{
"@id": 4,
"id": 7,
"name": "TestChildCategory",
"description": "This is test child category",
"editTime": "2016-03-23T11:40:19",
"editedBy": null,
"createTime": "2016-03-23T11:40:19",
"createdBy": 10,
"type": "SubCategory",
"status": "New",
"childs": [
3,
{
"@id": 5,
"id": 9,
"name": "TestChildCategory",
"description": "This is test child category",
"editTime": "2016-03-23T11:40:20",
"editedBy": null,
"createTime": "2016-03-23T11:40:20",
"createdBy": 10,
"type": "Indicator",
"status": "New",
"childs": [],
"parents": [
2,
4
],
"opinions": [],
"timestamp": "2016-03-23T11:40:20",
"edited": "2016-03-23T11:40:20"
}
]
}
],
},
]
}
]
},
2,
4,
3,
5
]
}
我不想要数组中的数字(2,4,3,5),但我想要实际的对象。我怎么能这样做?
更新 我也经历了question 它是唯一的方法吗?