Connecting to multiple Databases using Torque

To begin with, let me say that ,  “Torque”  is an Object Relational Mapping(ORM) Tool for Java.
I have some expertise working with Torque when compared to iBatis and  Hibernate, so  I thought of sharing one of my experiences that I came across when I WAS using Torque[yes, that’s right I am not using Torque anymore].
The requirement here was to connect to two databases, fetch data from one database and insert it into another.  Fetching and inserting into Databases is a very basic thing that I would like not to discuss here (at least in this blog).
However, before we Fetch or Insert, there are few more operations that we need to perform, and one of those is “Establishing a Connection with the database”.
This write-up with a small example data explains us the concept of connecting to multiple DBs using the ‘Torque’ ORM tool.
torque.properties file appears to be like this
##  Oracle DB Properties
torque.database=default
torque.database.default.adapter=oracle
torque.dsfactory.default.factory=org.apache.torque.dsfactory.JndiDataSourceFactory
torque.dsfactory.default.jndi.path = java:/jdbc/consumers
torque.dsfactory.default.jndi.java.naming.factory.initial = org.apache.naming.java.javaURLContextFactory
torque.dsfactory.default.jndi.java.naming.factory.url.pkgs = javax.naming
##  Sql Server 2005 Properties
torque.database.mssqldb.adapter=mssql
torque.dsfactory.mssqldb.factory=org.apache.torque.dsfactory.JndiDataSourceFactory
torque.dsfactory.mssqldb.jndi.path=java:/consumers-sqlserver-ds
torque.dsfactory.mssqldb.jndi.java.naming.factory.initial = org.apache.naming.java.javaURLContextFactory
torque.dsfactory.mssqldb.jndi.java.naming.factory.url.pkgs=javax.naming
It is required to use a unique handle name for each and every DB we use. Here we will be using ‘default’ and ‘mssqldb’ as handles for oracle and MS Sql Server Databases respectively .
Note: ‘
a) default’ is used here to indicate that the oracle is used as the default DB. So it’s recommended not to interpret ‘default’ as a string similar to “mssqldb’’.
b) jdbc/consumers and consumers-sqlserver-ds  in the torque.properties are the   jndi-name(s) as mentioned in oracle-ds.xml
The handle names mentioned in torque.properties file are used in java code as shown in the code below
Connection oracleConn = null;
 Connection sqlServerConn = null;   
 try {
         / * Establishes Connection to oracle DB  */
          oracleConn = Torque.getConnection();
          / * Establishes Connection to SQL SERVERDB  */
         sqlServerConn = Torque.getConnection(“mssqldb’’”);
............
.............


      } catch (Exception e) {
      } finally {
   Torque.closeConnection(conn);
   Torque.closeConnection(sqlServerConn); 
}

Comments

Popular posts from this blog

Creating Custom Code Panels using InstallAnywhere

Get JBoss Version using Java Code

Server Migration from JBoss-4.0.5 to JBoss-4.2.3.GA