Working with root resources that inter relate
Foo and Bar are both Beans.
If FooResource is accessed via /foo/{id} and BarResource by /bar/{id} and Foo relates to Bar, should I return the URI for Bar or just the id for Bar? I presume the URI.
I encapsulate Foo in FooRepresentation and Bar in BarRepresentation and these types are actually what are returned by (Foo|Bar)Resource to Jackson. In the case of the related Bar, I use UriBuilder, using BarResource.class and foo.getBar().getId() to generate a URI.
The part where I am stumped is what is best if I wanted to change which Bar the Foo referenced. So I have the URI for the "new" Bar.. lets PUT or POST that to foo/1
At this point I am in FooResource with a method that has a constructed FooRepresentation parameter being passed to it. For direct properties, this makes sense, because I can use an injected FooRepository to merge changes.
Does it make sense to then create something like FooService that has a method setFooBar(Foo foo, Id barId) and that's where the multiple repositories are injected?
开发者_StackOverflow中文版If no, how do I go from URI -> BarResource -> Bar (not BarRepresentation) within a request to FooResource?
If I were within BarResource I could use UriInfo to extract the id parameter, which feels cleaner as well, rather than just parsing the id from the URI. So is there a way to get an instance of BarResource that will have appropriately injected @Context items such as UriInfo, from within FooResource?
Sticking to Jersey, what I've resolved to do is:
For a given root resource class, ensure that it has an obtainX() function which can use a service to get an instance of the referred entity via PathParams. This returns the actual domain entity, and also throws a 404 exception if not null.
Then another class would take the URI, use ResourceContext to get an instance of the resource, then use obtainX to get the entity. With this, any interrelationship between entities (which is only ever expressed via root entities) works. It's not the best and is definitely the least comfortable part of everything I'm doing in Jersey, but it works.
精彩评论