I have a Hibernate entity with self references
@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
}
So, obviously I was facing infinite recursion while deserializing the JSON when I was getting all the entities. So I added
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
above the class name. But now, the JSON only contains ids or numbers like
{
"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
]
}
I dont want numbers in the array (2, 4, 3, 5) but I want actual objects. How can I do that?
UPDATE I also went through the question so is it the only way to do it?