JBoss.orgCommunity Documentation

Chapter 14. Database Connectivity in TorqueBox

14.1. ActiveRecord
14.2. DataMapper
14.3. Raw JDBC
14.4. Distributed Transactions

Typical applications require the use of databases. Within the Rails community, ActiveRecord is one of the more popular database connectivity libraries. With traditional Ruby-based applications, you needed to require the correct ActiveRecord adapter for the database you were connecting to. Each adapter managed the communication between the client and the end database, directly mediating the connection.

Since TorqueBox is based on the JBoss Java environment, it has the capability to use enterprise-grade JDBC (Java Database Connectivity API) drivers. Rails applications can take advantage of these drivers by using the generic ActiveRecord JDBC adapter. The adapter will locate and activate the correct underlying Java JDBC adapter for the target database.

The most visible change required of applications using the JDBC-based ActiveRecord adapter involves the gems your application must rely on. Primarily you must rely on the activerecord-jdbc-adapter. This adapter is adjusts ActiveRecord configuration to use the JDBC version of any specified driver.

Additional gems need to be available to your system, depending on your target database:

These gems simply embody the Java JAR holding the actual underlying JDBC driver.

No changes to your application's database configuration is required. You still specify the correct driver name for the database, such as postgresql or sqlite3.

Not everyone uses ActiveRecord to connect to a database. TorqueBox also works well with DataMapper, and you don't have to do anything special. A Gemfile for an application which uses DataMapper to connect to a PostgreSQL database looks like this.

gem 'data_mapper', '~>1.1'
gem 'dm-core', '~>1.1'
gem 'dm-postgres-adapter', '~>1.1'
gem 'dm-migrations', '~>1.1'
gem 'dm-timestamps', '~>1.1'
gem 'dm-observer', '~>1.1'

Initializing DataMapper is unchanged.

DataMapper.setup(:default, 'postgres://user:pass@localhost/databasename')

It is also possible to use JDBC directly without the need for a object-relational mapping library. For more information on this, see the JRuby wiki.

TorqueBox includes support for distributed (XA) transactions. Depending on your database, you may need to alter its configuration to take advantage of transactions. See Chapter 15, TorqueBox Distributed Transactions for more details.