So today I created a new Rails app to demonstrate how to use Rails' controllers and views with some model classes from one of my earlier Java projects. My old app used the typical HibernateUtil singleton (section 1.2.5 of the Hibernate docs). I also liked the ActiveRecord pattern so my Java domain classes had some handy "find" methods. So in order to make this work in a Rails app, I installed the goldspike plugin:
script/plugin install http://jruby-extras.rubyforge.org/svn/trunk/rails-integration/plugins/goldspike
and then ran the rake task war:standalone:create
I copied the classes and lib directories from my old apps' WEB-INF directory to the WEB-INF directory in my Rails app and then generated a controller and modified it to look like this:
require 'java'
import 'com.example.domain.Person'
import 'com.example.util.HibernateUtil'
class PersonController < ApplicationController
def list
with_transaction do
@people = Person.find_all.to_a
@people.sort!{|p1, p2| p1.name.downcase <=> p2.name.downcase}
end
end
def with_transaction
begin
tx = HibernateUtil.session_factory.current_session.beginTransaction
yield
tx.commit
HibernateUtil.session_factory.current_session.close
rescue
tx.rollback
end
end
end
Finally, I added a list.rhtml template for the "list" action and voila! I have a Rails-ish app that uses Hibernate instead of ActiveRecord.