YOU ARE HERE: Home > Tech > J2EE > Article

Using iBATIS in web applications
By John Henry Xu This article was rated:
 
Printer Version Printer Friendly | Add As Favorite | Link to Article

About the Author

Dr. John Xu (also known as Jack Xu) is a seasoned system architect. He was chief architect for large distributed portals. He also developed search engine and Java forums. He can be reached by email xixu@yahoo.com.

iBATIS, as a SQL mapping technology, has been used in many Internet applications to simplify data persistence. SQL mapping technology is simple comparing to other OR mapping frameworks. And newer technologies such as spring framework can use iBATIS in data persistence.

The major reason that iBATIS becomes popular is its simplicity and its relationship to raw SQL.

iBATIS allows SQL statements appear in configuration files. Since the SQL is used in iBATIS, it has very few limitations when it is used to persist data.

In this example, we use iBATIS in a simple web application. The focus in this article is to expose steps of using iBATIS, so we write a real simple form input and a jsp file to process this input. Next article we will discuss how to use MVC framework such as struts and iBATIS.

To start this tutorial, you should have completed the tutorials of Using Struts and Hibernate (Part I), in which we have created a table in MySQL database. This table user_info2 is used in this application.

You should have installed an application server such as Tomcat for this application. We create a folder %TOMCAT_HOME%\webapps\ibatisapp for this web application. You should also have

1. Install iBATIS and configure JNDI

You need install iBATIS to use this application. You may download iBATIS from

http://ibatis.apache.org/

Current version is iBATIS version 2. We have downloaded iBATIS_DBL-2.1.5.582.zip file and expanded the file into folder C:\ibatis2, in which we can find and copy three jar files, ibatis-common-2.jar, ibatis-dao-2.jar, and ibatis-sqlmap-2.jar to %TOMCAT_HOME%\server\lib or

%TOMCAT_HOME%\webapps\ibatisapp\WEB-INF\lib.

You also need add a JNDI in Tomcat %TOMCAT_HOME%\conf\server.xml file under <Host> node:

List 1.1

<Context path="/ibatisapp" docBase="ibatisapp">

<Resource name="jdbc/getjobs" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="myguest" password="myapp"

driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql:///myapp" />

</Context>

assuming you have "myguest" as user name and "myapp" as password in your MySQL database.
Also check %TOMCAT_HOME%\webapps\ibatisapp\WEB-INF\web.xml and make sure the following lines is in web.xml

List 1.2

<resource-ref>
<res-ref-name>jdbc/getjobs</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

List 1.2, together with List 1.1, defines JNDI you need to connect to MySQL database.


2. Form input file


We create a JSP file that has a form for user inputting information. The source code is


List 2.1 iBatisForm.jsp

<html>
<head>
<title>http://www.usanalyst.com</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>


<form method="post" action="iBatisAction.jsp">
<table width="62%" border="0">
<tr>
<td width="49%">
<div align="right"><b>Email</b></div>
</td>
<td width="51%">
<input type="text" name="email" value="">
</td>
</tr>
<tr>
<td width="49%">
<div align="right"><b>First Name</b></div>
</td>
<td width="51%">
<input type="text" name="firstName" value="">
</td>
</tr>
<tr>
<td width="49%">
<div align="right"><b>Last Name</b></div>
</td>
<td width="51%">
<input type="text" name="lastName" value="">
</td>
</tr>
<tr>
<td width="49%">
<div align="right"><b>Phone</b></div>
</td>
<td width="51%">
<input type="text" name="phone" value="">
</td>
</tr>
<tr>
<td width="49%"> </td>
<td width="51%">
<input type="submit" value="Submit">
</td>
</tr>
</table>
</form>
</html>

This is a simple form that user can input data into it and submit. Start tomcat and type http://localhost:8081/ibatisapp/iBatisForm.jsp
You should see the screenshot as



3. Action File


The form is processed by iBatisAction.jsp, which utilized iBatis to save data into MySQL.


List 3.1 iBatisAction.jsp

<%@ page buffer="12kb" %>

<%@ page import="com.usanalyst.struts.*" %>
<%@ page import="java.io.Reader" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.io.IOException" %>

<%@ page import="org.apache.commons.logging.Log" %>
<%@ page import="org.apache.commons.logging.LogFactory" %>

<%@ page import="com.ibatis.common.resources.Resources" %>

<%@ page import="java.sql.*" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="com.ibatis.sqlmap.client.*" %>
<%@ page import="com.ibatis.sqlmap.client.event.*" %>
<%@ page import="java.util.Date" %>

<jsp:useBean id="HibernateUtil" scope="session"

class="com.usanalyst.hibernate.HibernateUtil" />
<%
String email=request.getParameter("email");
String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String phone=request.getParameter("phone");

String resource="com/usanalyst/struts/sqlMap-config.xml";
Reader reader=Resources.getResourceAsReader(resource);
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);

user_info user = new user_info();
user.setEmail(email);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setPhone(phone);
user.setRequestTime(new Date());
sqlMap.insert("insertUser", user);

out.println("<b>Your information has been saved by iBatis.");
%>

In this JSP file, you need read an iBATIS configuration file com/usanalyst/struts/sqlMap-config.xml.

sqlMap-config.xml defines the iBATIS properties.

4. iBATIS configuration files

The configuration file sqlMap-config.xml defines iBATIS persistence properties

List 4.1 sqlMap-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-config-2.dtd">

<sqlMapConfig>

<properties resource="com/usanalyst/struts/connection.properties" />
<transactionManager type="JDBC">
<dataSource type="JNDI">
<property name="DataSource" value="${DbJNDIPath}"/>
</dataSource>
</transactionManager>
<sqlMap resource="com/usanalyst/struts/user_info.xml" />
</sqlMapConfig>

It refers to a properties file connection.properties as


List 4.2 connection.properties

DbJNDIPath=java:comp/env/jdbc/getjobs

The variable DbJNDIPath has been used in sqlMap-config.xml


Resource file com/usanalyst/struts/user_info.xml is a file that maps SQL statements to data objects.


List 4.3 user_info.xml

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

-map-2.dtd">

<sqlMap namespace="user">

<insert id="insertUser" parameterClass="com.usanalyst.struts.user_info">
INSERT INTO user_info2
(userId,email,firstName,lastName,phone,requestTime)
values (#userId#,#email#,#firstName#,#lastName#,#phone#,#requestTime#)
<selectKey keyProperty="userId" resultClass="int">
select last_insert_id()
</selectKey>
</insert>
</sqlMap>

5. Data Objects


A data object class user_info has been defined for mapping with a table user_info2 in MySQL.

This data object class has been used in user_info.xml


List 5.1 user_info.java

package com.usanalyst.struts;
import java.util.Date;

public class user_info {

private int userId;
private String email;
private String firstName;
private String lastName;
private String phone;
private Date requestTime;

public user_info() {
}

public int getUserId() {
return userId;
}

public void setUserId(int userId) {
this.userId = userId;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public Date getRequestTime() {
return requestTime;
}

public void setRequestTime(Date requestTime) {
this.requestTime = requestTime;
}

}

6. Running the example


Let??s run the example.

Start web application server, and type http://localhost:8081/ibatisapp/iBatisForm.jsp

Type input for the user, you will see

Click Submit button you should see

If you check MySQL database, "Joe Storm" has been saved.

From above simple steps, you see how easy iBATIS is used to save user information to a
database.


Was this article helpful to you?yesno
1 of 1 people found this article helpful.



Related Publications
 
Using iBATIS and struts
Using iBATIS in web applications
Using Struts and Hibernate (Part III)
Using Struts and Hibernate (Part II)
Using Struts and Hibernate (Part I)
Using Hibernate In J2EE Applications (Part I)
Effective Ant Build For Developers
Introduction To Struts By Example
How To Build Custom JSP Tags (Part II)
How To Build Custom JSP Tags (Part I)
Configuring SSL on BEA WebLogic Server 8.1

(Registered users can post questions/comments)

 
 TLINKS SEARCH
Advanced Search
Help
 Recommended Links
Red Cross
Responding to hurricane katrina relieve. Donate today. It's a Great Feeling to Help.
http://www.redcross.org
Getusjobs.com
Getusjobs.com is the job site focused on American jobs. See the results that put us on top.
http://www.getusjobs.com
Database Tool
TLinkSoft® tools empowers developers, integrators and DBAs to be more productive.
http://www.cppunit.org/download.jsp
USAnalyst.com
USAnalyst.com provide a community for database analysts, business analysts, developer analysts and managers.
http://www.cppunit.org/article

Powered by Tlinks Systems