How to add relationships in JAX-RS via RESTful web service?

删除回忆录丶 提交于 2019-12-11 23:52:43

问题


OK I can GET POST PUT DELETE simple resources (entities) in my RESTful web service

ex.

/rest/foos
/rest/foos/1 

/rest/bars
/rest/bars/1

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

I have such approach to GET this relationships:

GET /rest/bars/1/foos 

Above returns collection of foos related with Bar(id=1)

I cosider maybe doing it this way:

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

Above will create new Foo object and make association between this new object and Bar(id=1).

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

Above updates Foo(id=2) if there is such association with Bar(id=1) or if there isn't such association and Foo(id=2) exists in Foo table such association will be made.

If I would like to add/update only Foo without association i made sth like below:

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

If I would like to remove Foo(id=2)

DELETE /rest/foos/2 

And if I only want to delete association between Bar(id=1) and Foo(id=2)

DELETE /rest/bars/1/foos/2 

What do you think about such approach? And how would you handle this correctly?


回答1:


Regarding your OneToMany relation How to model parent child entities via REST might help you.

The association with its parent is an attribute of the child resource so the OneToMany relation should be managed on the many side.

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

Is OK if your foos are only possible in connection with a bar but if they can also exist without a bar you should use a dedicated foo resource not subordinate to the bar resource. Think aggregation or composition.

And if I only want to delete association between Bar(id=1) and Foo(id=2)

DELETE /rest/bars/1/foos/2

I would not use this approach instead update the foo with id=2 to not be associated with bar 1 anymore. A DELETE /rest/bars/1/foos/2 should delete the full foo resource instead of only the association in my opinion.

Regarding ManyToMany relations you'll need a third resource to manipulate the join table directly. To simplify this a little bit this resource will only need the POST and DELETE actions defined. POST to add a new associated pair: to ids, one for bar and one for foo. DELETE to remove such a pair.



来源:https://stackoverflow.com/questions/32540754/how-to-add-relationships-in-jax-rs-via-restful-web-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!