Ruby on Rails with Spring, Hibernate and JPA

I’m leading a discussion on this topic at the Charlotte BarCamp tomorrow.

Many companies who have invested a lot of time and money in Java technology could still benefit greatly from Ruby on Rails by using it to build new sites that make use of their backend Java based services.

Here’s an example of an RSpec test that uses a Java DAO, provided by Spring to access a database with JPA / Hibernate.

it "should retrieve an Account by ID" do
  load_data "dao/accounts.xml"
  dao = spring.getBean 'accountDao'
  acct = dao.find "5000"
  acct.should_not be_nil
  acct.getName.should == "Alpha"
end

It’s surprisingly easy to use a Spring context here by adding the following method to my spec_helper:

import 'org.springframework.context.support.ClassPathXmlApplicationContext'
import 'org.springframework.core.io.ClassPathResource'
 
def spring(context_file="beans.xml")
  java.lang.Thread.current_thread.context_class_loader =
      JRuby.runtime.getJRubyClassLoader
  @ctx ||= ClassPathXmlApplicationContext.new context_file
end

Using that helper I am able to access any component managed by Spring. As designed, Spring will wire up any required dependencies, provide a pooled database connection, and handle any other configuration necessary so that the bean returned is ready to use.

My test also uses DBUnit to load an XML fixture. It can do that by adding this method to spec_helper:

import 'org.dbunit.database.DatabaseConnection'
import 'org.dbunit.dataset.xml.FlatXmlDataSet'
import 'org.dbunit.operation.DatabaseOperation'
 
def load_data(data_file)
  begin
    @dataSource ||= spring.getBean 'dataSource'
    @conn ||= DatabaseConnection.new @dataSource.getConnection
    @dataset ||=
        FlatXmlDataSet.new(ClassPathResource.new(data_file).getInputStream)
    DatabaseOperation::CLEAN_INSERT.execute(@conn, @dataset)
  rescue
    print "load_data error: ", $!, "\n"
  end
end

DBUnit provides a useful way to load data fixtures into a test database. The reason I’m using DBUnit instead of the more common YAML format used in Rails apps, is so that I can make use of the fixtures already available in the Java project.

Here’s what my DBUnit fixture looks like:

This combination of technologies seems like a pretty powerful combination to me, especially for those companies who are entrenched in Java and are looking for a way to improve their productivity.

I’m interested to know who else is using this type of setup. Leave a comment and describe your experience.

Leave a Reply