Ibatis Presentation - Changed

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 42

iBatis

December, 2006
What is iBATIS ?

A popular tool that works at the SQL level but abstracts


the use of JDBC completely.
• DAO framework and SQL Maps framework
• Started by Clinton Begin
• part of Apache since February 2005
• Version for .NET available since June 2005
• Simple idea
• Statements are defined in an XML file
• Specify a SQL string with parameter placeholders
• In case of a query ,result columns are mapped to a result
objects
• provides support for caching query results
• pluggable cache strategies

Commercial in Confidence 2
Don'ts

• does not provide transparent persistence


• no change detection for retrieved objects
• strictly focus on mapping of input parameters and result
values for SQL statements
• When using Java Beans as values, a low-level kind of O/R
mapping is provided
• Nested objects must be dealt with explicitly, no implicit
cascading of update or delete operations

Commercial in Confidence 3
Does

•Compared to high-level transparent persistence,mapping at the SQL level has the


following advantages:
• Retain the full power of SQL
• Set-based updates and deletes
• Aggregate functions like AVG, SUM, and COUNT can be used
without any restrictions
• Mapping a domain object to fields across multiple tables is
straightforward, allowing any granularity
• Works with legacy database schemas
•An application’s data access code is still responsible for:
• Explicitly updating modified objects, keeping track of potential
modifications, and managing relationships between objects
• Converting application-level values to database-compatible values
• Full blown transparent persistence tools (like JDO & Hibernate ) offer a more
convenient way for working with persistent objects.

Commercial in Confidence 4
Architecture

Commercial in Confidence 5
How it Works ?
Data Mapper provides a very simple framework for using XML descriptors to
map Java Beans, Map implementations, primitive wrapper types (String,
Integer…) and even XML documents to an SQL statement. The following is a
high level description of the lifecycle:
1. Provide an object as a parameter (either a JavaBean, Map or primitive
wrapper).
The parameter object will be used to set input values in an update
statement, or where clause values in a query, ...
2. Execute the mapped statement.
This step is where the magic happens. The Data Mapper framework will
create a PreparedStatement instance, set any parameters using the provided
parameter object, execute the statement and build a result object from the
ResultSet.
3. In the case of an update, the number of rows effected is returned. In the case of
a query, a single object, or a collection of objects is returned. Like parameters,
result objects can be a JavaBean, a Map, a primitive type wrapper or XML.
Commercial in Confidence 6
Installing iBatis.

• Installing the iBATIS Data Mapper framework is simply a matter of


placing the appropriate JAR files on the classpath
• iBATIS comes with the following JAR files that should be on the
classpath.

File Name Description Required

ibatis-common.jar iBATIS Common Yes


Utilities
ibatis-sqlmap.jar iBATIS Data Mapper Yes
Framework
ibatis-dao.jar iBATIS Data Access No
Framework

Commercial in Confidence 7
SqlMapConfig.xml

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


<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="128"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="false"
/>
<transactionManager type="JDBC" >
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="oracle.jdbc.OracleDriver"/>
<property name="JDBC.ConnectionURL"
value="jdbc:oracle:thin:@AICDB:1521:PARTYCH"/>
<property name="JDBC.Username" value="PARTYCH"/>
<property name="JDBC.Password" value="PARTYCH"/>
</dataSource>
</transactionManager>

<typeAlias alias=“rental” type=“com.firstapex.demo.vo.RentalDetailsVO” />


<sqlMap resource="com/firstapex/demo/dao/ibatis/rental.xml"/>

Commercial in Confidence 8
</sqlMapConfig>
typeAlias Element

The <typeAlias> Element


The typeAlias element simply allows you to specify a shorter name to
refer to what is usually a long, fully qualified classname.
For example:
<typeAlias alias="shortname" type="com.long.class.path.Class"/>
Note : if you specify the alias for a class file in the sqlMapConfig file , it will be
applicable to all the sqlMap files that are included in the sqlMapConfig file .

<SqlMap XML File >

<SqlMapConfig.xml>

Commercial in Confidence 9
sqlMap Element

The <sqlMap> Element


The sqlMap element is used to explicitly include an SQL Map or another SQL
Map Configuration file.Each SQL Map XML file that is going to be used by the
SqlMapClient instance, must be declared. The SQL Map XML files will be loaded as a
stream resource from the classpath or from a URL.
Eg:
<!-- CLASSPATH RESOURCES -->
<sqlMap resource="com/firstapex/demo/dao/ibatis/maps/rental.xml" />
<sqlMap resource="com/firstapex/demo/dao/ibatis/maps/customer.xml" />
<sqlMap resource="com/firstapex/demo/dao/ibatis/maps/address.xml" />
<!-- URL RESOURCES -->
<sqlMap url="file:///c:/config/ rental.xml " />
<sqlMap url="file:///c:/config/ customer.xml " />
<sqlMap url="file:///c:/config/ address.xml" />

Commercial in Confidence 10
SQL Map XML File

• XML descriptor which maps the JavaBeans, Map implementations,primitive


wrapper types (String, Integer …) and even XML documents to an SQL statement
• You can define and use as many SQL Map files as you like
<sqlMap>
<cacheModel/> *
<typeAlias/> *
<parameterMap/> *
<resultMap/> *
<statement/> *
<select | insert | update | delete | procedure/> *
</sqlMap>

Commercial in Confidence 11
Statement Element

• The <statement> element is a general "catch all“ statement that can be


used for any type of SQL statement
• It’s a good idea to use one of the more specific elements
• provide more intuitive XML DTD and sometimes additional features

<statement> <delete>

<insert> <update>

<select> <procedure>

Commercial in Confidence 12
parameterMap

The <parameterMap> is responsible for mapping JavaBeans properties to the parameters of a


statement.The parameterMap contains any number of parameter mappings that map directly to the
parameters of a statement.
<parameterMap id=”parameterMapName” [class=”com.domain.Product”]>
<parameter property =”propertyName” [jdbcType=”VARCHAR”] [javaType=”string”]
[nullValue=“-9999”] [typeName=”{REF or user-defined type}”]
[resultMap=someResultMap] [mode=IN|OUT|INOUT]
[typeHandler=someTypeHandler] [numericScale=2]/>
<parameter …… />
</parameterMap>
ParameterMapName – Name of the parameterMap that can be used for further reference.
propertyName – is the name of the field variable defined in the vo.
jdbcType – This attribute is used to explicitly specify the database column type of the parameter to be
set by this property. Some JDBC drivers are not able to identify the type of a column. This attribute is
normally only required if the column is nullable.
javaType –This attribute is used to explicitly specify the Java property type of the parameter to be set.

Commercial in Confidence 13
parameterMap Ext

nullValue –The null attribute is used to specify an outgoing null value replacement. What this means
is that when the value is detected in the JavaBeans property, a NULL will be written to the database.
typeHandler-- This attribute is used to specify a custom type handler that will be used for this
property instead of the default iBATIS type system. If specified, this value should be the fully
qualified name of a class that implements either the com.ibatis.sqlmap.engine.type.TypeHandler
interface or the com.ibatis.sqlmap.client.extensions.TypeHandlerCallback interface. This value
overrides any global type handler that might otherwise be applied to this property.
Eg:
<parameterMap class="com.firstapex.demo.vo.AddressVO" id="customerDetailsParameterMap" >
<parameter property="custNo" javaType="int" jdbcType="NUMBER"/>
<parameter property="custName" javaType="String" jdbcType="VARCHAR" nullValue="-999"/>
<parameter property="job" javaType="String" jdbcType="VARCHAR" nullValue="-999"/>
<parameter property="ssn" javaType="String" jdbcType="VARCHAR" nullValue="-999"/>
<parameter property="licensed" nullValue="-999" typeHandler="booleanHandler"/>
<parameter property="licencseNo" javaType="String" jdbcType="VARCHAR" nullValue="-
999"/>
<parameter property="rentalID" javaType="String" jdbcType="VARCHAR" nullValue="-999"/>
</parameterMap>

Commercial in Confidence 14
parameterMap Ext

Eg:
<parameterMap class="rental" id="rentalParameterMap" >
<parameter property="rentalID" javaType="string" jdbcType="VARCHAR" />
<parameter property="vehicalType" javaType="string" jdbcType="VARCHAR" nullValue="-
999"/>
<parameter property="vehicleNo" javaType="string" jdbcType="VARCHAR" nullValue="-999"/>
<parameter property="fromDate" jdbcType='DATE' nullValue="-999"/>
<parameter property="toDate" jdbcType='DATE' nullValue="-999"/>
</parameterMap>
Usage:
<insert id="insertRentalByMap" parameterMap="rentalParameterMap" >
INSERT INTO RENTAL_DETAILS
(RENTALID,VEHICLETYPE,VEHICLENO,FROMDATE,TODATE)
VALUES(?,?,?,?,?)
</insert>
In the above example, the JavaBeans properties will be applied to the parameters of the Mapped
Statement insertRentalByMap in the order they are listed.

Commercial in Confidence 15
InLine ParameterMap

The syntax for declaring parameterMaps is very verbose


There is a more popular syntax that simplifies the definition and reduce code
The simple syntax is as follows:
#propertyName# - OR -
#propertyName:jdbcType# - OR -
#propertyName:jdbcType:nullValue#

Eg:
<insert id="insertRental" parameterClass="rental" >
INSERT INTO RENTAL_DETAILS
(RENTALID,VEHICLETYPE,VEHICLENO,FROMDATE,TODATE)
VALUES
(#rentalID:VARCHAR:-999#,#vehicalType:VARCHAR:-999#,
#vehicleNo:VARCHAR:-999#,#fromDate:DATE#,#toDate:DATE#)
</insert>
• When using inline parameters, you cannot specify the null value replacement without also specifying
the type. You must specify both due to the parsing order.

Commercial in Confidence 16
Primitive Type Parameter

It is not always necessary or convenient to write a JavaBean just to use as a parameter.


Eg:
<select id="getRentalVOUsingParameter" resultClass="rental" parameterClass="string">
select RENTALID as rentalID,VEHICLETYPE as vehicalType,VEHICLENO as vehicalNo ,
FROMDATE as fromDate,TODATE as toDate from RENTAL_DETAILS where RENTALID =
#value#
</select>

•Here #value# will be substituted by the value of the string that is being passed by the ibatis.
•Primitive types are aliased for more concise code.
• For example, “int” can be used in place of “java.lang.Integer”.
“string” in place of “java.lang.String”

Commercial in Confidence 17
Map Type Parameters

• Using Map as parameter.

<select id=“getRentalVOMapAsInput” parameterClass=“java.util.Map”>


select RENTALID as rentalID,VEHICLETYPE as vehicalType,VEHICLENO as vehicalNo ,
FROMDATE as fromDate,TODATE as toDate from RENTAL_DETAILS
where RENTALID = #rentalID# and VEHICLETYPE = #type#
</select>

• Map must contain keys named rentalID and type. The values referenced by those keys would be of the
appropriate type, such as Integer and String .

Commercial in Confidence 18
resultMap

• ResultMaps are an extremely important component of Data Mapper


• The <resultMap> is responsible for mapping JavaBean properties to the
columns of a ResultSet
<resultMap id=”resultMapName” class=”some.domain.Class” [extends=”parent-resultMap”]
[groupBy=“some property list”]>
<result property=”propertyName” column=”COLUMN_NAME”
[columnIndex=”1”] [javaType=”int”] [jdbcType=”NUMERIC”]
[nullValue=”-999999”] [select=”someOtherStatement”]
[resultMap=“someOtherResultMap”]
[typeHandler=“com.mydomain.MyTypehandler”] />
</resultMap>
extends – This attribute can be optionally set to the name of another resultMap upon which to base a
resultMap.
This is similar to extending a class in Java, all properties of the super resultMap will be included as part
of
the sub resultMap.
groupBy –This attribute is used to specify a listof properties in this resultMap that are used to identify
unique rows in the returned result set.
Commercial in Confidence 19
ResultMap Ext

property-This attribute is the name of a JavaBeans property.


column -This attribute value is the name of the column in the ResultSet from which the value will be
used to populate the property.
columnIndex -attribute value is the index of the column in the ResultSet from which the value will be
used to populate the JavaBeans property.
nullValue – This attribute specifies the value to be used in place of a NULL value in the database. So
if a NULL is read from the ResultSet, the JavaBean property will be set to the value specified by the
nullValue attribute instead of NULL.
select - This attribute is used to describe a relationship between objects and automatically load
complex property types. The value of the statement property must be the name of another mapped
statement. The value of the database column (the column attribute) that is defined in the same property
element as this statement attribute will be passed to the related mapped statement as the parameter.
resultMap – This attribute is used to describe a nested resultMap that can be reused in the result
mapping.This can be used in 1:1 relationships or 1:N relationships.
typeHandler – This attribute is similar to the typeHandler in parameterMap.

Commercial in Confidence 20
ResultMap Example
<resultMap class="rental" id="rentalResultMap" >
<result property="rentalID" column="RENTALID" />
<result property="vehicalType" column="RENTALID" />
<result property="vehicleNo" column="VEHICLENO" />
<result property="fromDate" column="FROMDATE" />
<result property="toDate" column="TODATE" />
<result property="customer" column="RENTALID" select="customer.getCustomerForRentalId" />
</resultMap>
<select id="getRentalVO" parameterClass="String" resultMap="rentalResultMap">
select * from RENTAL_DETAILS where RENTALID = #value#
</select>
<resultMap class="customerVO" id="customerVOResultMap">
<result property="custNo" column="CUSTNO"/>
<result property="custName" column="CUSTNAME"/>
<result property="job" column="JOB"/>
<result property="ssn" column="SSN"/>
<result property="licensed" column="LICENSED" typeHandler="booleanHandler"/>
<result property="licencseNo" column="LICENSENO"/>
<result property="address" column="CUSTNO" select="address.getAddressByID"/>
<result property="rentalID" column="RENTALID"/>
</resultMap>
<select id="getCustomerForRentalId" resultMap="customerVOResultMap" parameterClass=“string">
select * from CUSTOMER_DETAILS where RENTALID = #value#
</select>
<N+1 Problem>

Commercial in Confidence 21
Implicit Result Maps
If you have a very simple requirement ,there is a quick way to implicitly specify a result map by setting a resultClass
attribute of a mapped statement. The trick is that you must ensure that the result set returned has column names
(or labels/aliases) that match up with the write-able property names of your JavaBean.

Eg:
<select id="getRentalVOUsingResultClass" resultClass="rental" parameterClass="string">
select RENTALID as rentalID,VEHICLETYPE as vehicalType,VEHICLENO as vehicalNo ,
FROMDATE as fromDate,TODATE as toDate from RENTAL_DETAILS where RENTALID = #value#
</select>

Commercial in Confidence 22
Map Results

Result Maps can also conveniently populate a Map instance such as HashMap or TreeMap. Collections of
such objects (e.g. Lists of Maps) can also be retrieved using the APIs (Like queryForList()).
Map types are mapped exactly the same way as a JavaBean, but instead of setting JavaBeans properties, the
keys of the Map are set to reference the values for the corresponding mapped columns.
Eg:
<resultMap id="rentalResultHashMap" class="java.util.HashMap">
<result property="rentalID" column="RENTALID" />
<result property="vehicalType" column="VEHICLETYPE" />
<result property="vehicleNo" column="VEHICLENO" />
<result property="fromDate" column="FROMDATE" />
<result property="toDate" column="TODATE" />
</resultMap>

<select id ="rentalHashMap" resultMap = "rentalResultHashMap" >


select * from rental_details;
</select>
By using parametrClass :
<select id ="rentalHashMap" resultClass = “java.util.HashMap" >
select * from rental_details;
</select>

Commercial in Confidence 23
SQL

Handling Special Characters

<select id =“getRentalVO” parameterClass=“int” resultClass=“int”>


select * from rental_details where RENTALID <![CDATA[ > ]]> #value#
</select>
Reusing SQL Fragments

<select id =“getRentalVO” parameterClass=“int” resultClass=“int”>


select * from rental_details where VEHICLETYPE like #value#
</select>
Moving the common part.
<sql id =“select_rental_details”>
Select * from rental_details where
</sql>
<select id =“getRentalVO” parameterClass=“int” resultClass=“int”>
<include refid =“select_rental_details”/>
VEHICLETYPE like #value#
</select>
Commercial in Confidence 24
Complex Properties : N+1 selects problem

• The problem with this solution is, that whenever a rental object is loaded, 2 SELECT’s in total
are executed.
• 1 to retrieve the rental details (main query)
• 1 queries to retrieve the related complex property customer details.
• seems trivial when loading a single rental object.
• if the query was run to load 10 rental objects , 1 additional queries would be executed for each
rental object
• 1 * 10 = 10 additional queries => N+1 or in this case 10 + 1 = 11.
This problem can be addressed using another query approach.

<Example>

Commercial in Confidence 25
Solution For Problem
<resultMap class="rental" id="rentalResultMap" >
<result property="rentalID" column="RENTALID" />
<result property="vehicalType" column="RENTALID" />
<result property="vehicleNo" column="VEHICLENO" />
<result property="fromDate" column="FROMDATE" />
<result property="toDate" column="TODATE" />
<!--<result property="customer" column="RENTALID" select="customer.getCustomerForRentalId" />-->
<result property="customer" column="RENTALID" resultMap="customer.customerVOResultMap"/>
</resultMap>
<resultMap class="customerVO" id="customerVOResultMap">
<result property="custNo" column="CUSTNO"/>
<result property="custName" column="CUSTNAME"/>
<result property="job" column="JOB"/>
<result property="ssn" column="SSN"/>
<result property="licensed" column="LICENSED" typeHandler="booleanHandler"/>
<result property="licencseNo" column="LICENSENO"/>
<result property="address" column="CUSTNO" select="address.getAddressByID"/>
<result property="rentalID" column="RENTALID"/>
</resultMap>
<select id="getRentalVOByJoin" parameterClass="String" resultMap="rentalResultMap">
select * from RENTAL_DETAILS , CUSTOMER_DETAILS
Where
RENTAL_DETAILS.RENTALID = CUSTOMER_DETAILS.RENTALID and
RENTAL_DETAILS.RENTALID = #value#
</select>
Commercial in Confidence 26
Lazy Loading vs. Joins

• using a join is not always better


• If the related object is rarely accessed then it might be faster to avoid the join …
• … and better to use the sub-select solution with lazy loading and byte-code enhancement
options enabled
• Currently lazy loading can only be set on the whole SQL Map config
<sqlMapConfig> sql-map-config.xml
<settings
cacheModelsEnabled="true"
lazyLoadingEnabled="true"
enhancementEnabled="true"/>

• Currently lazy loading can only be set on the whole SQL Map config

Commercial in Confidence 27
Mapping Results to XML document
<select id="getAddressXml" resultClass="xml" xmlResultName=“ADDRESS"
parameterClass="String">
select CUSTNO AS "CUSTOMER NO", PURPOSE AS "PURPOSE" LINE1 as "Addressline1" ,
LINE2as "Addressline2" ,LINE3 as "Addressline3" , LINE4 as "Addressline4" ,STATE
as "state" ,COUNTRY as "country" , PIN as "PIN NUMBER" from ADDRESS_DETAILS Where
CUSTNO = #customerID#;
</select>
Result:
<ADDRESS>
<CUSTOMER NO></CUSTOMER NO>
<PURPOSE></PURPOSE>
<Addressline1></Addressline1>
<Addressline2></Addressline2>
<Addressline3></Addressline3>
<Addressline4></Addressline4>
…..
</Address>
Commercial in Confidence 28
TypeHandlerCallback

• simple interface for custom type handlers.


• a type handler can perform customized processing before parameters are set on a
PreparedStatement
and after values are retrieved from a ResultSet.
• By using a custom type handler the framework can be extended
• to handle types that are not supported
• handle supported types in a different way
• a custom type handler might be used to implement booleans in the database
using "Y" and "N" instead of the more typical 0/1.

Commercial in Confidence 29
TypeHandlerCallback - Example
public class BooleanHandler implements TypeHandlerCallback {
private static final String YES = "Y";
private static final String NO = "N";
public Object getResult(ResultGetter getter) throws SQLException {
String s = getter.getString();
if (YES.equalsIgnoreCase(s)) {
return new Boolean(true);
} else if (NO.equalsIgnoreCase(s)) {
return new Boolean(false);
} else {
throw new SQLException("Unexpected value " + s + " found where "+ YES + " or " + NO + " was expected.");
}
}
public void setParameter(ParameterSetter setter, Object parameter) throws SQLException {
boolean b = ((Boolean) parameter).booleanValue();
if (b) {
setter.setString(YES);
} else {
setter.setString(NO);
}
}
public Object valueOf(String arg0) {
// TODO Auto-generated method stub
return null;
Commercial in Confidence 30
}
}
Dynamic Mapped Statement
• A very common problem with working directly with JDBC is dynamic SQL
• normally very difficult to work with SQL statement
• that change not only the values of parameters
• but which parameters and columns are included at all
• The typical solution is usually a mess of conditional if-else statements and string
concatenations
• The Data Mapper API provides an elegant solution that can be applied to any mapped statement
element
Eg:
<select id=“dynamicGetRentalVO” resultMap = “rentalParameterMap”>
select * from RENTAL_DETAILS
<dynamic prepend=“WHERE”>
<isNotNull prepend=“AND” property=“vehicalType”>
VEHICLETYPE = # vehicalType #
</isNotNull>
<isGreaterThan prepend="and" property=“rentalID" compareValue="0">
RENTALID = #rentalID#
</isGreaterThan>
<dynamic>
order by rentalID
</select>

Commercial in Confidence 31
Binary Conditional Attributes

<isEqual> Checks the equality of a property and a value, or another property.


<isNotEqual> Checks the inequality of a property and a value, or another property.
<isGreaterThan> Checks if a property is greater than a value or another property.
<isGreaterEqual> Checks if a property is greater than or equal to a value or another property.
<isLessThan> Checks if a property is less than a value or another property.
<isLessEqual> Checks if a property is less than or equal to a value or another property.

Unary Conditional Elements

<isPropertyAvailable> Checks if a property is available (i.e is a property of the parameter bean)


<isNotPropertyAvailable>Checks if a property is unavailable (i.e not a property of the parameter bean)
<isNull> Checks if a property is null.
<isNotNull> Checks if a property is not null.
<isEmpty> Checks to see if the value of a Collection, String or String.valueOf() property is null or empty (“” or size() < 1).
<isNotEmpty> Checks to see if the value of a Collection, String or String.valueOf() property is not null and not empty (“” or size() < 1).

Commercial in Confidence 32
Caching Mapped Statement Results

The results from a Query Mapped Statement can be cached simply by specifying the cacheModel
parameter
The cache model is configured within the SQL map using the cacheModel element cache model
uses a pluggable framework
• MEMORY – uses reference type to manage the cache behavior
• LRU – uses a Least Recently Used algorithm
• FIFO – uses a First In First Out algorithm
• OSCACHE – uses the OSCache 2.0 caching engine

Eg:
<cacheModel id=“rental-cache" type =“MEMORY" readOnly=”true” serialize=”false”>
<flushInterval hours="24"/>
<flushOnExecute statement="insertRental"/>
<flushOnExecute statement=“updateRental”/>
<property name=”cache-size” value=”1000” />
<property name="reference-type" value="WEAK"/>
</cacheModel

Commercial in Confidence 33
Programming with the DataMapper:
insert(), update(), delete(): These methods are specifically meant for DML Operations.
public Object insert(String statementName, Object parameterObject) throws SQLException
public Object insert(String statementName) throws SQLException
public int update(String statementName, Object parameterObject) throws SQLException
public int update(String statementName) throws SQLException
public int delete(String statementName, Object parameterObject) throws SQLException
public int delete(String statementName) throws SQLException
Query:
queryForObject():There are three versions of queryForObject(), one that returns a newly allocated object,
and another that uses a pre-allocated object that is passed in as a parameter. The latter is useful for objects
that are populated by more than one statement.
public Object queryForObject(String statementName,Object parameterObject) throws
SQLException
public Object queryForObject(String statementName) throws SQLException
public Object queryForObject(String statementName, Object parameterObject, Object
resultObject) throws SQLException

Commercial in Confidence 34
API
queryForList(): There are four versions of queryForList().
The first executes a query and returns all of the results from that query.
The second is like the first, but does not accept a parameter object.
The third allows for specifying a particular number of results to be skipped (i.e. a starting point) and also the
maximum number of records to return. This is valuable when dealing with extremely large data sets
The fourth is like the third, but does not accept a parameter object.

public List queryForList(String statementName, Object parameterObject) throws SQLException


public List queryForList(String statementName) throws SQLException
public List queryForList(String statementName, Object parameterObject, int skipResults, int maxResults) throws
SQLException
public List queryForList(String statementName, int skipResults, int maxResults) throws SQLException
queryWithRowHandler(): This method allows you to process result sets row by row but using the result object.
The row handler is an instance of a class that implements the RowHandler interface.
The RowHandler interface has only one method as follows:
public void handleRow (Object valueObject);

This method will be called on the RowHandler for each row returned from the database.

void queryWithRowHandler (String statementName,Object parameterObject, RowHandler rowHandler) throws


SQLException
void queryWithRowHandler (String statementName, RowHandler rowHandler) throws SQLException
Commercial in Confidence 35
API
queryForPaginatedList(): This very useful method returns a list that can manage a subset of data that can be
navigated forward and back. This is useful in displaying search results where large data meets the search criteria but
only few rows will be displayed.The PaginatedList interface includes methods for navigating through pages
(nextPage(), previousPage(), gotoPage()) and also checking the status of the page (isFirstPage(), isMiddlePage(),
isLastPage(), isNextPageAvailable(), isPreviousPageAvailable(), getPageIndex(), getPageSize())
public PaginatedList queryForPaginatedList(String statementName,Object parameterObject, int
pageSize) throws SQLException
public PaginatedList queryForPaginatedList(String statementName, int pageSize) throws SQLException

queryForMap(): This method provides an alternative to loading a collection of results into a list. Instead it loads the
results into a map keyed by the parameter passed in as the keyProperty.
public Map queryForMap (String statementName, Object parameterObject, String keyProperty) throws
SQLException
public Map queryForMap (String statementName, Object parameterObject, String keyProperty, String
valueProperty) throws SQLException
flushDataCache(): These methods provide a programmatic way of flushing the data caches. The method without
arguments will flush all data caches.The no-argument method clears all the the data Cache.
public void flushDataCache()
public void flushDataCache(String cacheId)

Commercial in Confidence 36
Spring DAO Support

•The DAO (Data Access Object) support in Spring is primarily aimed at making it easy to work with
different data access technologies (like JDBC, Hibernate, EJB3 or iBATIS) in a standardized way.
• This allows to switch between them fairly easily and to code without worrying about catching exceptions
that are specific to each technology.
• replaces DAOFactory classes with configurations and dependency injection
• easy configuration of DAO using dependency injection
• base DaoSupport classes for popular persistence frameworks JDBC, iBATIS, Hibernate, Toplink, EJB3,

Commercial in Confidence 37
Spring Integration
• converts exceptions to a common exception hierarchy
• template classes reduce redundant code
• opens and closes necessary resources (such as database connections)
Eg:
<!-- Web SqlMap setup for iBATIS Database Layer -->
<bean id="sqlMapConfig" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation">
<value>/WEB-INF/sqlMapConfig.xml</value>
</property>
</bean>
<!-- iBatis DAO using the JNDI DataSource -->
<bean id=“rentalQueryDao" class="com.firstapex.demo.dao.ibatis. RentalDAOImpl">
<property name="dataSource" ref="dataSource"/>
<property name="sqlMapClient" ref="sqlMapConfig"/>
</bean>
public class RentalDAOImpl extends SqlMapClientDaoSupport implements IRentalDAO {
public RentalVO getRentalVO(String id) {
return (RentalVO) getSqlMapClientTemplate().queryForObject("getRentalVO", id);
}Commercial in Confidence 38
Settings Element

• The <settings> elements allows to configure various options and optimizations for the SqlMapClient instance
• The <settings> element and all its attribute are optional Always refer to mapped statements by a fully qualified
name (combination of the sqlMap name and the statement name)

maxRequests maximum number of threads that can execute an SQL statement at a time
maxSessions number of sessions (or clients) that can be active at a given time
maxTransactions Maximum number of threads that can enter a transaction at a time
cacheModelsEnabled Globally enables or disables caching
lazyLoadingEnabled Globally enables or disables lazy loading
enhancementEnabled Enables runtime bytecode enhancements
useStatementNamespaceAlways refer to mapped statements by a fully qualified name (combination of the sqlMap name and the statement name)

<sqlMapConfig.xml>

Commercial in Confidence 39
Transaction Manager and Data Source

• <transactionManager> configures the transaction management services for a SQL Map


• The type attribute indicates which transaction manager to use <sample>

JDBC Allows JDBC to control the transaction


JTA Uses JTA global transaction such that SQL Map activities can be included as part of a distributed transaction
EXTERNAL Allows you to manage transaction on your own (transactions will not be committed as part of the framework lifecycle)

• SimpleDataSourceFactory (SIMPLE) – based on iBATIS connection pooling implementation


• DbcpDataSourceFactory (DBCP) – uses Jakarta DBCP (Database Connection Pool) to provided connection pooling services
• JndiDataSourceFactory (JNDI) – retrieves DataSource from a JNDI context
Syntax:
<dataSource type="SIMPLE">
<property value="${driver}" name="JDBC.Driver" />
<property value="${url}" name="JDBC.ConnectionURL" />
<property value="${username}" name="JDBC.Username" />
<property value="${password}" name="JDBC.Password" />
</dataSource>
<transactionManager type="JDBC" >
<dataSource type="JNDI">
<property name="DataSource" value=“JNDI NAME"/>
</dataSource>
Commercial in Confidence
</transactionManager> 40
On-line Resources

• Apache iBATIS Site


• http://ibatis.apache.org/
• Frequently Asked Questions

http://opensource2.atlassian.com/confluence/oss/display/IBATIS/Frequently+Asked+Qu
estions
• Article: iBatis Dao
• http://www.onjava.com/pub/a/onjava/2005/08/10/ibatisdao.html
• Article: Using iBatis SQL Maps for Java Data Access
• http://www.developer.com/db/article.php/3346301
• Spring Framework
• http://www.springframework.org

Commercial in Confidence 41

You might also like