users@jersey.java.net

[Jersey] Handling Transactions

From: <charles_overbeck_at_yahoo.com>
Date: Thu, 24 Mar 2011 00:36:24 +0000 (GMT)

Hello,

I want to begin a Hibernate transaction at the beginning of every
request into my Jersey app, and commit or roll it back at the end. When
there is an error, I want to return a response body with details about
the error -- I have a JAXB bean that defines the error format.

One way Hibernate recommends handling this scenario is by creating a
Filter:

http://community.jboss.org/wiki/OpenSessioninView

The problem with this approach is that if I get an error on the
commit() or rollback(), it won't be super-easy for me to create the
error body. Not impossible, but I won't be in Jersey then, so I won't
be able to take advantage of the JAXB/MessageBodyWriters.

So I found this thread that looks useful:

http://markmail.org/thread/orcctyu7hczx3d5w#query:+page:1+mid:zczy5mguc
n5qoolt+state:results

I could basically move the code from the Hibernate filter from my first
link, splitting it into a ContainerRequestFilter and a
ContainerResponseFilter. But I have 3 questions that aren't 100% clear
to me from that thread:

1) Paul says "if the resource throws an exception that is not mapped.
The exception will get passed through to the container and response
filters will not be called." If I have a @Provider that implements
ExceptionMapper<Throwable>, I'm covered here, right?

2) Paul also says "a filter declared before TransactionManagementFilter
throws an exception. This breaks the filter chain". If I don't have any
other filters, I don't have to worry about that. Well, I guess that
answer is pretty obvious. But just checking.

3) I don't understand the need for CloseableService in Adam's sample
code. Couldn't the ContainerResponse.filter() method also call
Transaction.ensureTransactionClosed()? Just making sure it's not a
different way of handling the closing the transaction, or if it is
something really necessary that I'm missing. I haven't used Closeable.
Is it for the case that something slips through 1 or 2, above? But
haven't we ensured that nothing will slip through?

I'm using Jersey 1.1.5.1. As in the above thread, I'm also not using
Spring, and would prefer to keep it that way.

Does anybody handle this this way, or maybe in a different way? Any
thoughts?

Thanks in advance,

Charles