I have web project with jpa(2.1) and hibernate(5.3.6). I have to do some servlets which have to save and retrieve me some data. So, if I have two classes:
public class Parent{
@Column(name="id")
private int id;
@Column(name="name")
private String name;
...
@OneToMany(orphanRemoval = true, mappedBy = "parent")
@Cascade({ CascadeType.ALL })
private List<Child> childs = new ArrayList<Child>();
}
and
public class Child{
@Column(name="id")
private int id;
@Column(name="name")
private String name;
...
@ManyToOne(fetch = FetchType.LAZY)
@Cascade({ CascadeType.ALL })
@JoinColumn(name = "parentId", foreignKey = @ForeignKey(name = "MyForeignKey"), nullable = true, updatable = true, insertable = true)
private Parent parent;
}
I have two cases:
I need to get the parent with all childs but when serializing i want to see just child's id, like:
[{ "id":1, "name": "parent1", "childs":[{ "id":10 }, { "id":18 }] }]
I need to get no matter which child and to see all properties, like:
[{ "id":10, "name": "child10" }]
I tried with gson library annotation on different fields
@Expose(serialize="false", deserialize="true")
but I can't achieve both of behaviors ( first case and second case), i get or:
parent ->
[{
"id":1,
"name": "parent1"
}]
with separate child ->
[{
"id":10,
"name": "child10"
}]
or
parent ->
[{
"id":1,
"name": "parent1",
"childs":[{
"id":10
},
{
"id":18
}]
}]
with separate child ->
[{
"id":10
}]
So, can you help me please with this problem? It's possible to achieve both case 1 and 2 in separate requests like I want?
Thank you.