Adding the Database access code to the Action class
At the end of part 2, we developed two screens (JSPs) and the
Action class. The TestForm had a simple form to take an input
String, shortname to search and pass it to the Action class.
The Action class searches the employee table for this shortname
and returns the list of employees. The TestResult page displays
it back to the user.
In this article we will modify Action class to use CASTOR
instead of plain JDBC, to ‘search’ for employees from a
database. To begin, keeping things simple lets just
replace the ‘getEmps’ method of the Action class to use CASTOR.
That is we will add all the code in Action class itself. Then,
after we demonstrate this simplistic way, we will discuss
separating out the "common" code for CASTOR, to a utility
class.
NOTE: This is just an attempt to demonstrate ‘read only’
database access from STRUTS, using CASTOR. For further details
on CASTOR, its transactional capabilities and other details
refer to the CASTOR project site.
Lets start with the TestActionHandler. We will add the following
import statements to the class:
import org.xml.sax.ContentHandler;
import org.exolab.castor.jdo.*;
import org.exolab.castor.persist.spi.Complex;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.mapping.Mapping;
import org.apache.xml.serialize.*;
import javax.sql.*;
import java.sql.*;
import java.util.Hashtable;
import java.util.Enumeration;
The perform method remains the same. No change there. The only
change will be in the 'getEmps' method as discussed. The completed
code for the class can be found at The Open Stack website, look for
"TestActionHandler class with CASTOR JDO Code". Lets start with
adding the two XML files that CASTOR uses. We will add the
following two variables to the method.
String DatabaseFile = "database.xml";
String MappingFile = "mapping.xml";
The database.xml file defines the database connection related
configuration. The mapping.xml file defines your O/R mapping,
i.e., it maps your objects to the back-end database tables.
We will create these files and keep them under the class tree. You
should probably store these two files under the source tree and
copy those to the "classes" directory during build. In our case
these two files ultimately need to go to:
WEB-INF\classes\com\openstack\struts\testapp directory.
Please refer to the TheOpenStack
Project page for details about "build" using Ant build
tool, for one way of automating this.
Let us look at the sample database.xml file for the MySQL database:
<!DOCTYPE databases PUBLIC "-//EXOLAB/Castor JDO Configuration
DTD Version 1.0//EN" "http://castor.exolab.org/jdo-conf.dtd">
<database name="openstack" engine="mysql" >
<driver url="jdbc:mysql://localhost/openstack"
class-name="org.gjt.mm.mysql.Driver">
</driver>
<mapping href="mapping.xml" />
</database>
If you are using another Database & driver, you will need to
change the values for driver URL (the name of the driver class
with complete path and access information). The "URL" will
depend on the database you are using. For the MySQL database, we
are using a database instance called "openstack" and no user
id/password. Some other "URL" strings may have the RDBMS server/
hostname, port number, instance name, along with the other
information. Please refer to your driver documentation for this.
Using Connection Pooling with Castor:In the above example
we are using the MySQL JDBC drive class directly. A better
option would be to use a Data source that allows connection
pooling. If your driver implements the JDBC 2.0 optional
package(The MySQL driver we downloaded does) you could set up
the database as:
<database name="openstack" engine="mysql" >
<data-source class name="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
<params server-name="localhost"
database-name="openstack" port="3306" />
</data-source>
<mapping href="mapping.xml" />
</database>
Next step is to complete the basic setup to instruct CASTOR to
use the database and mapping files and define the database to be
used.
Mapping dbMap = null;
JDO castorJDO = null;
Database mySQLDB = null;
//load the mapping file
dbMap= new Mapping( getClass().getClassLoader() );
dbMap.loadMapping
( getClass().getResource( MappingFile ) );
//load the databse file
castorJDO = new JDO();
castorJDO.setConfiguration(
getClass().getResource DatabaseFile ).toString() );
castorJDO.setDatabaseName( "openstack" );
Now we are ready to fire a query and get the results. Here is
the relevant code:
mySQLDB = castorJDO.getDatabase();
mySQLDB.begin();
OQLQuery empQuery = mySQLDB.getOQLQuery( "SELECT e FROM
com.openstack.struts.testapp.EmpBean e WHERE e.shortname LIKE $1 ");
empQuery.bind("%"+ searchStr + "%");
QueryResults results = empQuery.execute(Database.ReadOnly);
So far not too different, right? Here comes the part when the
code itself demonstrates the value of using a JDO framework like
CASTOR:
while ( results.hasMore() )
{
emp = ( EmpBean) results.next();
empList.add(emp);
}
Compare this against the following code snippet from the last
article (part 2):
while (rs.next()) {
emp = new EmpBean();
emp.setShortname(rs.getString("shortname"));
emp.setFirstname (rs.getString("firstname"));
emp.setLastname(rs.getString("lastname"));
empList.add(emp);
}
As you can see we do not have to hard code the column names in
the code. This is just one advantage. There are many others such
as transaction support, caching and so on. Refer to the CASTOR
web site for more.
Please look at the completed code of the Action class, for
further details. Now the question is where do we specify the
mapping of the database columns to the attributes of 'EmpBean'?
Lets use a simple but neat tool for that:
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|