advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

tutorials : Using CASTOR for DB Access from STRUTS :

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:

How to Add Java Applets to Your Site

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.

 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 34
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

IBM Brings Developers Into the Cloud
Apache at 10: You Can't Buy Us
Microsoft's CodePlex Foundation Moving Forward
Apple Claims 100,000 Apps, Google Analyzes Them
Nokia Latest to Play Opera Mobile 10 Browser
PayPal Opens Up Payment Platform to Devs
Ubuntu Linux 9.10 'Karmic Koala' Starts Its Climb
IBM Links Rational Developer Tools, Tivoli Apps
Libraries Give Vista Apps a Windows 7 Look
Ubuntu: The 'Default Alternative' to Windows?

Delivering Web-based Embedded Fonts in CSS 3
Adobe Helps PHP Developers Create Rich Internet Applications
Java Developers Finding a Home at Adobe Flex
Virtualization Delivers a Dynamic Infrastructure
Consuming XML Web Services in iPhone Applications
Build a More Agile Business with IBM
POJO-Based Solutions for LDAP Access: One Good, One Better
IBM Offers Enhanced Measurement and Management for Energy Usage
IBM Helps Transformation to an Information-Based Enterprise
Top Five Touch UI-Related Design Guidelines

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs