Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
Using iBatis SQL Maps for Java Data Access
[go: Go Back, main page]

developer.com
Search EarthWeb
CodeGuru | Gamelan | Jars | Wireless | Discussions
Navigate developer.com
Architecture & Design  
Database  
Java
Languages & Tools
Microsoft & .NET
Open Source  
Project Management  
Security  
Techniques  
Voice  
Web Services  
Wireless/Mobile
XML  
Technology Jobs  

   Developer.com Webcasts:
  The Impact of Coding Standards and Code Reviews

  Project Management for the Developer

  Defining Your Own Software Development Methodology

  more Webcasts...




See the Winners!


Developer Jobs

Be a Commerce Partner
Desktop Computers
PDA Phones & Cases
Data Center Solutions
Auto Insurance Quote
Condos For Sale
Compare Prices
Shop
GPS Devices
Computer Deals
Shop Online
Baby Photo Contest
Server Racks
Promotional Pens
Sell Used Cell Phones

 
Biz Resources
Contact Management Software
Domain Name Services
Internet Security


Download these IBM resources today!
e-Kit: IBM Rational Systems Development Solution
With systems teams under so much pressure to develop products faster, reduce production costs, and react to changing business needs quickly, communication and collaboration seem to get lost. Now, theres a way to improve product quality and communication.

Webcast: Asset Reuse Strategies for Success--Innovate Don't Duplicate!
Searching for, identifying, updating, using and deploying software assets can be a difficult challenge.

eKit: Rational Build Forge Express
Access valuable resources to help you increase staff productivity, compress development cycles and deliver better software, fast.

Download: IBM Data Studio v1.1
Effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life.

eKit: Rational Asset Manager
Learn how to do more with your reusable assets, learn how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse.
Developer News -
'WinTel' to Fund Parallel Computing Research    March 19, 2008
Sybase Broadens iPhone's Enterprise Appeal    March 18, 2008
Eclipse Targets Runtime With New Project    March 17, 2008
Apple, Google Gear Up For Developers    March 14, 2008
Free Tech Newsletter -

Intel Whitepaper: Improve Security and Control of Your PCs

Using iBatis SQL Maps for Java Data Access
By Michael Klaene

Go to page: 1  2  3  Next  

Finding the best approach when accessing a database from Java can be a daunting task. The most common solution is to program directly to the JDBC (Java Database Connectivity) APIs. The result is hard-to-read source files, bloated with complex code that has nothing to do with business logic. To make matters worse, JDBC does nothing to address the natural differences that usually exist between a system's object model and its relational data model. This necessitates still more code to glue these disparate views together. There is clearly a need for tools to assist us in this area.

The iBATIS Database Layer, written by Clinton Begin, is a collection of open-source components that assist Java developers with data access. The most important of these components is the SQL Maps framework. SQL Maps provides an efficient way to graph database values to Java objects through the use of XML configuration files. This article will use the latest production release of SQL Maps, 1.3.1, to demonstrate how SQL Maps work using a series of examples. It will then conclude with a discussion of the benefits of using iBatis SQL Maps.

A First Look

To view SQL Maps in action, I will use a simple demo application that allows employees to make conference room reservations. It will not be possible to cover SQL Maps in its entirety, but hopefully there will be enough here to entice you to visit the iBATIS site and explore the project in greater detail.

There are two tables to consider in our application, conference_rooms and room_reservations. The conference_rooms table identifies conference_rooms by id and name. The field number_of_seats can be used to guage the size of a room. The room_reservations table, linked to conference_rooms by room_id, stores reservation times and the team ('development team', 'accounting team') making the reservation. For simplicity's sake, there is a one-to-one mapping between these tables, conference_rooms and room_reservations, and the JavaBeans ConferenceRoom and RoomReservation.

Given this setup, let's first consider a code snippet that you might use if populating a ConferenceRoom bean with JDBC:

String roomToUse        = "Conf Room North";
ConferenceRoom confRoom = new ConferenceRoom();

try{
  Connection conn = dSrc.getConnection();
  PreparedStatement pstmt =
    conn.prepareStatement("SELECT room_id,room_name,number_of_seats,
                           room_active " +
     "FROM conference_rooms WHERE room_name = ?";
  pstmt.setString(1,roomToUse);
  rstst = ps.executeQuery();

  rstst.next();
  confRoom.roomId        = rstst.getInt(1);
  confRoom.roomName      = rstst.getString(2);
  confRoom.numberOfSeats = rstst.getInt(3);
  confRoom.roomActive    = rstst.getBoolean(4);

  rstst.close();
  pstmt.close();
}
catch(SQLException e) {
   throw newRuntimeException(e);
}
finally {
  conn.close();
}

As simple as the code's objective may be, it is complicated by JDBC 'plumbing.' Let's try this once again, the SQL Maps way:

String roomToUse = "Conf Room North";

ConferenceRoom confRoom = (ConferenceRoom) 
   sqlMap.executeQueryForObject("getConferenceRoomByName", roomToUse);

The SqlMap method, getQueryForObject, accepts two String parameters. The first parameter identifies the name of the mapped SQL statement we use to access the database. The second specifies a room name used in the query. The bean is instantiated, populated, and then returned, leaving us to focus our coding efforts on application logic.

Now, I want to step backwards through this example and examine what makes such clean code possible. To do this, we need to look at two additional items. The first is the SQL Map file. This file is an XML descriptor that contains our mapped SQL statements. At runtime, these statements are read into an application. When "getConferenceRoomByName" is referenced in Java, a PreparedStatement object executes the query and a ResultSet populates the bean. The demo application uses a single SQL Map file called Conferences.xml. An application may use several such SQL Map files.

<!Conferences.xml SQL Map file-->

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sql-map PUBLIC "-//iBATIS.com//DTD SQL Map 1.0//EN"
   "http://www.ibatis.com/dtd/sql-map.dtd">

<sql-map name="Conferences">
  <mapped-statement name="getConferenceRoomByName"
                    result-class="entities.ConferenceRoom">
    SELECT room_id         as roomId,
           room_name       as roomName, 
           number_of_seats as numberOfSeats,
           room_active     as roomActive
      FROM conference_rooms
      WHERE room_name = #value#
  </mapped-statement>
</sql-map>

The bulk of the "getConferenceRoomByName" mapped statement consists of SQL. The result-class attribute specifies the fully qualified Java object returned from a mapped statement. The #value# keyword denotes that a statement's parameter is either a String or a Java primitive, such as int.

The final piece of the puzzle is the SQL Map Configuration file:

<!SqlMapConfig.xml SQL Map configuration file-->

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sql-map-config PUBLIC "-//iBATIS.com
                                  //DTD SQL Map Config 1.0//EN"
   "http://www.ibatis.com/dtd/sql-map-config.dtd">
   
<sql-map-config>

  <datasource name = "hsql" 
    factory-class="com.ibatis.db.sqlmap.datasource.SimpleDataSourceFactory"
            default="true">
    <property name="JDBC.Driver" value="org.hsqldb.jdbcDriver"/>
    <property name="JDBC.ConnectionURL"
              value="jdbc:hsqldb:hsql://localhost/conferences"/>
    <property name="JDBC.Username" value="sa"/>
    <property name="JDBC.Password" value=""/> 
  </datasource>

  <sql-map resource="maps/Conferences.xml"/>
 
</sql-map-config>

The purpose of this file is two-fold. First, it configures a JDBC DataSource. In this case, it uses iBATIS' own DataSource implementation, SimpleDataSource. Secondly, the file declares each SQL Map file that an application uses. Our examples use the hsqldb database and a single Map file, Conferences.xml.

Upon application startup, we search the classpath for this configuration file and process it.

String resource = "maps/SqlMapConfig.xml";
Reader reader   = Resources.getResourceAsReader(resource);
SqlMap sqlMap   = XmlSqlMapBuilder.buildSqlMap(reader);

The configuration needs to happen but one time, prior to the calling of any mapped statements. The sqlMap instance could be a Singleton, or possibly a ServletContext object in a web application, that we retrieve when we need to call a mapped statement. The Resource class we are using is provided by iBATIS to read files from the classpath.

Go to page: 1  2  3  Next  


Tools:
Add www.developer.com to your favorites
Add www.developer.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed


Database Archives

Sun Success Story: Tocarema--Sun Studio provides the startup tools for an automated trading system.
Sun Studio can get you there faster, safer and more reliably. Download Sun Studio Now
Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.
Generate Complete .NET Web Apps in Minutes . Download Iron Speed Designer today.
RSA Whitepaper: Develop FIPS 140-validated Solutions for the Federal Government Using BSAFE Software



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Intel eBook: Managing the Evolving Data Center
IBM Whitepaper: Enterprise Information Integration: Deployment Best Practices for Low-Cost Implementation
Intel Clients PDF: Improve Security and Control of your PCs
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Intel Mobility PDF: Wireless Technologies and e-Learning--Bridging the Digital Divide
Avaya Article: How to Begin Developing with Avaya's Event Processing Language
Intel Multi-Core PDF: Comparing Multi-Core Processors for Server Virtualization
Avaya Article: Deep Dive--Event Processor Offers Familiar Tools for Creating Event-Driven SOA Apps
Intel Whitepaper: A Methodology for Threading Serial Applications (PDF)
HP eBook: Storage Networking , Part 1
F5 Whitepaper: Deploying SharePoint 2007? BIG-IP LTM with WebAccelerator Can Speed it up by 8x
Quest Whitepaper: Improving Oracle Database Performance Using Real-Time Visual Diagnostics
ServerWatch.com Article: Tip of the Trade--IP Address Management
Avaya Article: Event Processing Demands Real-Time Response for Communications-Enabled Business Applications
ITChannelPlanet.com Article: Enterprise Fixed-Mobile Convergence Can Be Lucrative
StoreVault Whitepaper: Introduction to Networked Storage
Intel Article: Transitioning Software to Future Generations of Multi-Core
Oracle eBook: Implementing Business Intelligence in Your Organization
Hoovers Article: Boost Employee Morale without Breaking the Bank
SAP Whitepaper: A Corporate Guide to Better Decisions Through IT
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
IBM Whitepaper: Transforming Legacy Apps into SOA
Internet.com eBook: All About Botnets
Intel Article: 8 Simple Rules for Designing Threaded Applications
Symantec Whitepaper: E-Mail Discovery--Worst-Case Scenarios Versus Best Practices
Ipswitch Whitepaper: Secure File Transfer In the Era of Regulatory Compliance
Symantec Whitepaper: A Unified, Proactive Approach to Endpoint Security
Intel Whitepaper: Best Practices for Developing and Optimizing Threaded Applications
Symantec Whitepaper: Emerging Trends in Fighting Spam
Microsoft Partner Program Article: How to Market Your Technology Solutions
Avaya Article: Opening Telephony to Microsoft Developers
Symantec Whitepaper: Best Practices for IM Archiving & Compliance
Intel Article: The Challenges of Developing Multithreaded Processing Pipelines
Symantec Article: Guarding the Corporate Gateway
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Foundations of Parallel Programming, Part One
Microsoft Web Seminar: Windows Mobile 6.0 Training for ISV Developers
IBM Webcast: Asset Reuse Strategies for Success--Innovate Don't Duplicate!
HP Video: Page Cost Calculator
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Epicor Webcast: Requirements to Consider When Looking at ITSM Tools
Intel Video: Three Must-Knows for Parallelism
Microsoft Partner Program Video: The Secrets to Partner Success
Rational Asset Manager: Succeed with Asset-based Development
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
IBM eKit: IBM Rational Systems Development Solution
IBM eKit: Rational Asset Manager
IBM Developer Kit: Web 2.0
IBM Download: Data Studio v1.1
NXPowerLite: Desktop Edition Software Trial
Iron Speed Designer Application Generator
Symantec IM Detection Utility
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Intel Servers/Workstations Demo: Dual-Core Intel Itanium 2 Processor
Flash Demo: IBM Information Server Blade
HP Demo: StorageWorks EVA4400
IBM Demo: Adding Security to your Web Services Digital Signatures
IBM Demo: Deployment Tracking with Rational ClearQuest and ClearCase
IBM Overview Video: Next Generation Data Warehousing
IBM Tutorial: Intro to XML User Interface Language (XUL) Development
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES