On Mar 9, 2009, at 8:03 PM, Jaka JanĨar wrote:
> On 9. Mar 2009, at 18:10, Paul Sandoz wrote:
>>> Because of this, I need to:
>>> - perform some one-time intialization (build an
>>> EntityManagerFactory)
>>> - put the try{start;service;commit}catch{rollback} code somewhere.
>>>
>>> What is the appropriate place to do this when using JAX-RS?
>>>
>>
>> There are no hooks defined in JAX-RS itself to do Web application
>> initialization, per and post dispatching.
>>
>> Perhaps you can write a ServletFilter? to do pre/post processing
>> before and after invocation on the Servlet?
>>
>
> I don't think that will work as I need to do it depending on the
> resource (I was giving the simplest possible example initially) :/
>
> I have a master database and multiple node databases. The nodes are
> different from the master, but otherwise the same.
>
> The api would expose the master database and any number of node
> databases, through an api like this:
>
> /status
> /some-other-global-stuff
> /nodes/1/resource-foo
> /nodes/1/resource-bar
> /nodes/2/resource-foo
> /nodes/2/resource-bar
> ...
>
> So for every request
> - a connection/transaction to the master database is made, and
> - optionally a connection to one of the nodes is made.
>
> Now, creating the connections is not a problem. I can make something
> like:
>
> @Path("/nodes")
> class NodeListResource {
> @Path("/{id}")
> public NodeResource getNodeResource(@PathParam("id") int id) {
> EntityManager em = ... create entity manager for the node with
> specified id...;
> return new NodeResource(em);
> }
> }
>
> Which would work nicely and in a very elegant fashion. But I have no
> way to commit/roll back.
>
> I can achieve it at Servlet level with either a custom servlet or a
> servlet filter, but I'd have to manually be parsing resource URLs,
> which I *REALLY* don't want. So that's why I want to do it *within*
> JAX-RS boundaries.
>
> Any ideas? Pretty please? :)
>
You could obtain something from the servlet context that creates and
manages the EntityManager instances. The filter can then cleanup those
instances.
For a more elegant solution you will need to use something Jersey
specific with resource specific filters, or use an IoC framework like
Spring+AOP.
Paul.