1

I have a complex class, that have many objects inside, when I do GET, I want to see the full object with all inner objects data, but when I POST, I only want to pass ID's for inner objects.

Example:

class ComplexObject {
    private InnerObject1 innerObject1;
    private InnerObject2 innerObject2;

    //setters and getters
}

when I do GET, I want to retrieve the full JSON, that's the easy part, but when I save the ComplexObject, I want to only pass the id's for the innerObject1 and innerObject2, not the whole object.

How can I achieve that?

kdureidy
  • 960
  • 9
  • 26

2 Answers2

1

You shouldn't use Hibernate entities for sending and receiving data in REST calls. Use separate objects for this - data transfer object (DTO) - What is Data Transfer Object?. In your case, it may be ComplexObjectWithIds which contains only ids:

@POST
@Path("/complex-object")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postComplexObject(ComplexObjectWithIds complexObjectWithIds)

And ComplextObjectFull with full data:

@GET
@Path("/complex-object")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ComplextObjectFull getComplexObject()
Community
  • 1
  • 1
Justinas Jakavonis
  • 8,220
  • 10
  • 69
  • 114
0

When you post the object you can parse the JSON you send and retrieve the needed objects by ID in your controller, and then rebuild the object there and send the full object to be created.

For example, let's say you have an ObjectController, and on the post route you will build a complex JSON.

//Post request to this method
public void addObject(@RequestBody Object obj) {
    Object newObj = new Object(obj);

    //Get the full objects by id
    InnerObject innerObj = innerObjectService.findById(obj.innerObjectId);

    //Build the full new object
    newObj.setInnerObj(innerObj);

    //Create the object
    ...
 }
Ionut Robert
  • 254
  • 1
  • 3
  • 12
  • Yes, it's very similar to DTO's. Actually it's a better practice to use DTO's instead of the base Objects as the other answer pointed out. – Ionut Robert Jan 13 '17 at 15:22