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

Sample for lift-ng: Micro-burn 1.0.0 released

During a last few evenings in my free time I've worked on mini-application called micro-burn. The idea of it appear from work with Agile Jira in our commercial project. This is a great tool for agile projects management. It has inline tasks edition, drag & drop board, reports and many more, but it also have a few drawbacks that turn down our team motivation.

Motivation

From time to time our sprints scope is changing. It is not a big deal because we are trying to be agile :-) but Jira's burndowchart in this situation draw a peek. Because in fact that chart shows scope changes not a real burndown. It means, that chart cannot break down an x-axis if we really do more than we were planned – it always stop on at most zero.

Also for better progress monitoring we've started to split our user stories to technical tasks and estimating them. Original burndowchart doesn't show points from technical tasks. I can find motivation of this – user story almost finished isn't finished at all until user can use it. But in the other hand, if we know which tasks is problematic we can do some teamwork to move it on.

So I realize that it is a good opportunity to try some new approaches and tools.

Tools

I've started with lift framework. In the World of Single Page Applications, this framework has more than simple interface for serving REST services. It comes with awesome Comet support. Comet is a replacement for WebSockets that run on all browsers. It supports long polling and transparent fallback to short polling if limit of client connections exceed. In backend you can handle pushes in CometActor. For further reading take a look at Roundtrip promises

But lift framework is also a kind of framework of frameworks. You can handle own abstraction of CometActors and push to client javascript that shorten up your way from server to client. So it was the trigger for author of lift-ng to make a lift with Angular integration that is build on top of lift. It provides AngularActors from which you can emit/broadcast events to scope of controller. NgModelBinders that synchronize your backend model with client scope in a few lines! I've used them to send project state (all sprints and thier details) to client and notify him about scrum board changes. My actor doing all of this hard work looks pretty small:

Lift-ng also provides factories for creating of Angular services. Services could respond with futures that are transformed to Angular promises in-fly. This is all what was need to serve sprint history:

And on the client side - use of service:


In my opinion this two frameworks gives a huge boost in developing of web applications. You have the power of strongly typing with Scala, you can design your domain on Actors and all of this with simplicity of node.js – lack of json trasforming boilerplate and dynamic application reload.

DDD + Event Sourcing

I've also tried a few fresh approaches to DDD. I've organize domain objects in actors. There are SprintActors with encapsulate sprint aggregate root. Task changes are stored as events which are computed as a difference between two boards states. When it should be provided a history of sprint, next board states are computed from initial state and sequence of events. So I realize that the best way to keep this kind of event sourcing approach tested is to make random tests. This is a test doing random changes at board, calculating events and checking if initial state + events is equals to previously created state:



First look

Screenshot of first version:


If you want to look at this closer, check the source code or download ready to run fatjar on github.During a last few evenings in my free time I've worked on mini-application called micro-burn. The idea of it appear from work with Agile Jira in our commercial project. This is a great tool for agile projects management. It has inline tasks edition, drag & drop board, reports and many more, but it also have a few drawbacks that turn down our team motivation.

Mock Retrofit using Dagger and Mockito

Retrofit is one of the most popular REST client for Android, if you never use it, it is high time to start. There are a lot of articles and tutorial talking about Retrofit. I just would like to show how to mock a REST server during develop of app and i...Retrofit is one of the most popular REST client for Android, if you never use it, it is high time to start. There are a lot of articles and tutorial talking about Retrofit. I just would like to show how to mock a REST server during develop of app and i...