Search code examples
ruby-on-railsactiverecordjrubyjxls

Access java.sql.connection from ActiveRecord JRuby?


I am using Jruby and Rails 3 with jxls, a Java library to generate reports in Excel.

The jxls API has a ReportManagerImpl which takes a java.sql.Connection in its constructor.

ReportManager reportManager = new ReportManagerImpl( conn, beans );

In my non-working code, ReportQuery is a ActiveRecord object. The Jruby looks like this:

conn = ReportQuery.connection
rm = Java::NetSfJxlsReport::ReportManagerImpl.new(conn, params)

But ActiveRecord::Base.connection returns not a java.sql.Connection, but a ActiveRecord::ConnectionAdapters::JdbcAdapter.

How can I access the underlying java.sql.Connection object from JRuby?

The error message I get is:

2012-12-28 17:28:08,000 [main] WARN org.apache.commons.jexl2.JexlEngine - ![3,149]: 'rm.exec('SELECT d.name depname, e.name empname, age, payment, bonus, birthDate FROM employee e, department d where d.id = e.depid order by age desc');' method invocation error org.jruby.exceptions.RaiseException: (NoMethodError) undefined method `createStatement' for #<ActiveRecord::ConnectionAdapters::JdbcAdapter:0x13ba673> 

Solution

  • Use .jdbc_connection method on a ActiveRecord connection to access the raw JDBC connection in JRuby:

    ActiveRecord::Base.connection.jdbc_connection