0

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:

  1. 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 }] }]

  2. 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.

Peter Šály
  • 2,848
  • 2
  • 12
  • 26
Cati
  • 53
  • 6
  • Tagging your question as JSON rather than JPA would mean it accurately reflects what you want. JPA != JSON, JPA doesn't do serialisation –  Feb 21 '19 at 16:39
  • Possible duplicate of [Ignore fields from Java object dynamically while sending as JSON from Spring MVC](https://stackoverflow.com/questions/23101260/ignore-fields-from-java-object-dynamically-while-sending-as-json-from-spring-mvc) – Peter Šály Feb 22 '19 at 11:28

0 Answers0