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

Inconsistent Dependency Injection to domains with Grails

I've encountered strange behavior with a domain class in my project: services that should be injected were null. I've became suspicious as why is that? Services are injected properly in other domain classes so why this one is different?

Constructors experiment

I've created an experiment. I've created empty LibraryService that should be injected and Book domain class like this:

class Book {
def libraryService

String author
String title
int pageCount

Book() {
println("Finished constructor Book()")
}

Book(String author) {
this()
this.@author = author
println("Finished constructor Book(String author)")
}

Book(String author, String title) {
super()
this.@author = author
this.@title = title
println("Finished constructor Book(String author, String title)")
}

Book(String author, String title, int pageCount) {
this.@author = author
this.@title = title
this.@pageCount = pageCount
println("Finished constructor Book(String author, String title, int pageCount)")
}

void logInjectedService() {
println(" Service libraryService is injected? -> $libraryService")
}
}
class LibraryService {
def serviceMethod() {
}
}

Book has 4 explicit constructors. I want to check which constructor is injecting dependecies. This is my method that constructs Book objects and I called it in controller:

class BookController {
def index() {
constructAndExamineBooks()
}

static constructAndExamineBooks() {
println("Started constructAndExamineBooks")
Book book1 = new Book().logInjectedService()
Book book2 = new Book("foo").logInjectedService()
Book book3 = new Book("foo", 'bar').logInjectedService()
Book book4 = new Book("foo", 'bar', 100).logInjectedService()
Book book5 = new Book(author: "foo", title: 'bar')
println("Finished constructor Book(Map params)")
book5.logInjectedService()
}
}

Analysis

Output looks like this:

Started constructAndExamineBooks
Finished constructor Book()
Service libraryService is injected? -> eu.spoonman.refaktor.LibraryService@2affcce2
Finished constructor Book()
Finished constructor Book(String author)
Service libraryService is injected? -> eu.spoonman.refaktor.LibraryService@2affcce2
Finished constructor Book(String author, String title)
Service libraryService is injected? -> null
Finished constructor Book(String author, String title, int pageCount)
Service libraryService is injected? -> null
Finished constructor Book()
Finished constructor Book(Map params)
Service libraryService is injected? -> eu.spoonman.refaktor.LibraryService@2affcce2

What do we see?

  1. Empty constructor injects dependencies.
  2. Constructor that invokes empty constructor explicitly injects dependencies.
  3. Constructor that invokes parent's constructor explicitly does not inject dependencies.
  4. Constructor without any explicit call declared does not call empty constructor thus it does not inject dependencies.
  5. Constructor provied by Grails with a map as a parameter invokes empty constructor and injects dependencies.

Conclusion

Always explicitily invoke empty constructor in your Grail domain classes to ensure Dependency Injection! I didn't know until today either!

Turing completeness II

Well, as I wrote in the previous post, sed is a Turing complete language. We can use it to implement some simple algorithms, or even a dc interpreter. But what does it really mean? How complex tasks may we achieve using plain sed?What about writin...Well, as I wrote in the previous post, sed is a Turing complete language. We can use it to implement some simple algorithms, or even a dc interpreter. But what does it really mean? How complex tasks may we achieve using plain sed?What about writin...