Setting up a datasource
Written by Joseph Ottinger
One of the first things web application developers seem to get wrong is connecting to a database. Usually, they follow the introduction to JDBC, which tells them to use Class.forName(), then manually get the connection, use it, then close it. This is fine for learning (since it steps through the whole process) but is a nasty performance hit.
After this discovery is made, some developers simply resign themselves to poor performance, seemingly deciding that "It's only Java, how could it be any faster?" Others keep looking, and find connection pooling packages. Connection pooling is creating a set of database connections, to be retrieved on demand, which eliminates the largest bottleneck. However, while this may be the only good approach on simple servlet containers such as Tomcat or Jetty, J2EE suggests using the application server itself to handle database connections, and production-ready application servers (such as Orion) do, indeed, support this.
In Orion, you create a connection by modifying the $ORION/config/data-sources.xml file. In this file, you can create a data source by creating an XML node that looks something like this:
class="com.evermind.sql.DriverManagerDataSource"
name="Hypersonic"
location="jdbc/HypersonicCoreDS"
xa-location="jdbc/xa/HypersonicXADS"
pooled-location="jdbc/HypersonicPooledDS"
ejb-location="jdbc/HypersonicDS"
connection-driver="org.hsqldb.jdbcDriver"
username="sa"
password=""
url="jdbc:HypersonicSQL:./database/defaultdb"
inactivity-timeout="30"
/>
This node creates four JNDI references to the same database: one is "normal," the "jdbc/HypersonicCoreDS", another is managed by Orion's transaction manager, the third is pooled, and the fourth is for use by the EJB container. (I'm not precisely sure of the differences between the transaction-managed and the EJB datasource.)
Once you've created your datasource in this manner, you can get a JDBC connection via JNDI, with the following code:
Context ctx=new InitialContext();
DataSource ds=(DataSource)ctx.lookup("jdbc/HypersonicDS");
Connection conn=ds.getConnection();
Don't forget to close your resources when you're done with them!
Copyright © 2007 IronFlare AB