Hibernate annotations + Spring transactions in OSGI

On our new project we decided to develop backend as services deployed on Servicemix 4.2. To make it easier for developers more familiar with ‘traditional’ web applications based on spring+hibernate stack it should (at least partially) resemble such application. Therefore, we want to have following bundles:

  • model –  containing hibernate classes
  • dao – implemented using hibernate template
  • service – interfaces for bundles implementing webservices, also controlling transactions, validation and similar stuff

So far, so good. Additional requirements are:

  • hibernate is configured using annotations
  • we use declarative transaction management with spring @Transactional annotation

Now, the question is – how to achieve it in OSGI environment? There are some tutorials on the web, but I haven’t found anything about this particular configuration, so I want to share our solution – as it wasn’t as straightforward as one might expect.

Hibernate bundle

The very first problem was the structure of hibernate jars themselves. It turned out that simple

wrap:mvn:org.hibernate:hibernate:3.3.1.GA

is not enough when one wants to use annotations. The problem is that both hibernate-core, and hibernate-annotations are using same package, namely org.hibernate.cfg. This is pretty anti-OSGI design, as OSGI bundle can use package exported by exactly one bundle.

The solution is of course pretty simple – we have to create our own bundle, which embeds both hibernate jars. This can be achieved with following maven-bundle-plugin configuration:

          

    *;uses:="org.hibernate";version=3.3.1.GA
    !*
    *;scope=compile|runtime;type=!pom;inline=true

Of course, you have to add hibernate dependencies to pom.

Session factory and transaction management

Servicemix has its own JTA TransactionManager, and at first I wanted to use it for managing our hibernate transactions. Unfortunatelly it turned to be somewhat tricky, so I decided to use simple solution, i.e. org.springframework.orm.hibernate.HibernateTransactionManager. It is declared in our dao bundle and exported as OSGI service:

	

    org.springframework.transaction.PlatformTransactionManager

Then, in service bundle we import it, and configure declarative transactions:


So far, it doesn’t look much more complicated than in traditional, monolithic war application. But there is one more caveat:

org.hibernate.jdbc.ConnectionWrapper is not visible from class loader

At first I thought it’s a matter of some misconfigured import/export declarations in some of our bundles. However, after some googling it turned out that it’s Hibernate’s bug

It is caused by using Thread context classloader when obtaining connection. It looks that the bug itself is already fixed, but we didn’t want to change to Hibernate 3.5 just because of that.

It turns out that there is quire simple workaround – you just need to make Spring aspect that will set context classloader to proper one (i.e. bundle class loader) before opening hibernate session, and you’re done. But again, using Servicemix makes it slightly harded, as it turns out that using @AspectJ style poses some difficulties (see e.g. this thread).

But it turns out that there is pretty simple solution – use old, Spring 1.x-style aspects :). This requires a bit more boilerplate xml, but at least we got it working pretty quickly.

The aspect class, setting proper classloader:

public class AspectFix implements MethodInterceptor {

    public Object invoke(MethodInvocation invocation) throws Throwable {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        try {
            return invocation.proceed();
        }
            finally{ Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
    }

The xml config:


      .*

    *Service

      fix

Final remark – now the service bundle has to import org.hibernate.jdbc to make it all work – as its classloader is used to initialize connection now.

To sum up: this is definitely not the most elegant solution one can imagine- but it’s working.

You May Also Like

Simple trick to DRY your Grails controller

Grails controllers are not very DRY. It's easy to find duplicated code fragments in default generated controller. Take a look at code sample below. It is duplicated four times in show, edit, update and delete actions:

class BookController {
def show() {
def bookInstance = Book.get(params.id)
if (!bookInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])
redirect(action: "list")
return
}
[bookInstance: bookInstance]
}
}

Why is it duplicated?

There is a reason for that duplication, though. If you move this snippet to a method, it can redirect to "list" action, but it can't prevent controller from further execution. After you call redirect, response status changes to 302, but after method exits, controller still runs subsequent code.

Solution

At TouK we've implemented a simple trick to resolve that situation:

  1. wrap everything with a simple withStoppingOnRender method,
  2. whenever you want to render or redirect AND stop controller execution - throw EndRenderingException.

We call it Big Return - return from a method and return from a controller at once. Here is how it works:

class BookController {
def show(Long id) {
withStoppingOnRender {
Book bookInstance = Book.get(id)
validateInstanceExists(bookInstance)
[bookInstance: bookInstance]
}
}

protected Object withStoppingOnRender(Closure closure) {
try {
return closure.call()
} catch (EndRenderingException e) {}
}

private void validateInstanceExists(Book instance) {
if (!instance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'book.label', default: 'Book'), params.id])
redirect(action: "list")
throw new EndRenderingException()
}
}
}

class EndRenderingException extends RuntimeException {}

Example usage

For simple CRUD controllers, you can use this solution and create some BaseController class for your controllers. We use withStoppingOnRender in every controller so code doesn't look like a spaghetti, we follow DRY principle and code is self-documented. Win-win-win! Here is a more complex example:

class DealerController {
@Transactional
def update() {
withStoppingOnRender {
Dealer dealerInstance = Dealer.get(params.id)
validateInstanceExists(dealerInstance)
validateAccountInExternalService(dealerInstance)
checkIfInstanceWasConcurrentlyModified(dealerInstance, params.version)
dealerInstance.properties = params
saveUpdatedInstance(dealerInstance)
redirectToAfterUpdate(dealerInstance)
}
}
}