How to add relationships to JAX-RS through a RESTful web service?

OK I CAN GET POST-DELETE DELETE simple resources (entities) in a RESTful web service

ex.

/rest/foos /rest/foos/1 /rest/bars /rest/bars/1 

But how to handle adding ex relationships. @OneToMany, @ManyToMany between these relationships using the RESTful web service. Suppose I have several Foo objects and several Bar objects, how to establish relations Bar 1 has Foo 3, etc.

I have an approach to GET this relationship:

 GET /rest/bars/1/foos 

Above returns the foos collection associated with Bar (id = 1)

I would say I can do it like this:

 POST /rest/bars/1/foos { # Foo json object } 

Above, create a new Foo object and create a relationship between this new object and Bar (id = 1).

 PUT /rest/bars/1/foos/2 { # Foo json object } 

Above updates to Foo (id = 2), if there is such a relationship with Bar (id = 1), or if there is no such association in the table Foo, and Foo (id = 2) exists, such an association will be executed.

If I would like to add / update only Foo without a link, I did sth as shown below:

 POST /rest/foos PUT /rest/foos/2 

If I wanted to remove Foo (id = 2)

 DELETE /rest/foos/2 

And if I want to remove the connection between Bar (id = 1) and Foo (id = 2)

 DELETE /rest/bars/1/foos/2 

What do you think of this approach? And how would you deal with this correctly?

0
source share
1 answer

Regarding your relationship, OneToMany How to model parent children via REST can help you.

Communication with your parent is an attribute of a child resource, so the OneToMany relationship must be managed from a large angle.

 PUT /rest/bars/1/foos/2 { # Foo json object } 

OK, if your foos is possible only in connection with bar , but if they can also exist without bar , you should use the allocated resource foo , not subordinate to the resource bar . Imagine aggregation or composition.

And if I want to remove the connection between Bar (id = 1) and Foo (ID = 2)

DELETE / rest / bars / 1 / foos / 2

I would not use this approach, instead I update foo with id=2 so that I no longer associate with bar 1. A DELETE /rest/bars/1/foos/2 should delete the full resource foo , not just the association, in my sight.

Regarding ManyToMany relationships, you will need a third resource to directly manage the connection table. To simplify this, this resource will require only certain POST and DELETE actions. POST to add a new related pair: in ids, one for bar and one for foo . DELETE to remove such a pair.

0
source

All Articles