iBatis course (beta)

79
Curso de iBatis For smarties

description

iBatis course (beta)

Transcript of iBatis course (beta)

Page 1: iBatis course (beta)

Curso de iBatis

For smarties

Page 2: iBatis course (beta)

Instalando iBatis

http://ibatis.apache.org/javadownloads.cgi

Archivos:• ibatis-2.3.4.726.zip

• Unziped• ibatis-2.3.4.726.jar

Page 3: iBatis course (beta)

Configurando iBatis

Page 4: iBatis course (beta)

Configurando iBatis

1. Crear el SqlMapConfig.xml

2. Crear el db.properties

3. Crear la clase java

4. Crear el mapping para esa clase

Page 5: iBatis course (beta)

El 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>

<properties resource="db.properties" />

<settings useStatementNamespaces="false"

cacheModelsEnabled="true"

enhancementEnabled="true"

lazyLoadingEnabled="true"

maxRequests="32"

maxSessions="10"

maxTransactions="5" />

<transactionManager type="JDBC">

<dataSource type="SIMPLE">

<property name="JDBC.Driver" value="${driver}" />

<property name="JDBC.ConnectionURL" value="${url}" />

<property name="JDBC.Username" value="${user}" />

<property name="JDBC.Password" value="${pword}" />

</dataSource>

</transactionManager>

<sqlMap resource="test/Encuesta.xml" />

</sqlMapConfig>

Page 6: iBatis course (beta)

El db.properties

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/encuesta

user=root

pword=mysql

Page 7: iBatis course (beta)

La clase Encuesta.javapackage enitity;

import java.util.Vector;

public class Encuesta {private int codigoEncuesta;private String descripcionEncuesta;private Vector preguntas ;

public int getCodigoEncuesta() {return codigoEncuesta;

}public void setCodigoEncuesta(int codigoEncuesta) {

this.codigoEncuesta = codigoEncuesta;}public String getDescripcionEncuesta() {

return descripcionEncuesta;}public void setDescripcionEncuesta(String descripcionEncuesta) {

this.descripcionEncuesta = descripcionEncuesta;}public Vector getPreguntas() {

return preguntas;}public void setPreguntas(Vector preguntas) {

this.preguntas = preguntas;}

}

Page 8: iBatis course (beta)

El mapa de la clase Encuesta.java<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="Encuesta">

<!-- Use type aliases to avoid typing the full classname every time. --><typeAlias alias="Encuesta" type="enitity.Encuesta" />

<resultMap id="EncuestaResult" class="Encuesta"><result property="codigoEncuesta" column="codigo_encuesta" /><result property="descripcionEncuesta" column="descripcion_encuesta" />

</resultMap>

<!-- Select with no parameters using the result map for Encuesta class.--><select id="selectAllEncuestas" resultMap="EncuestaResult">

select * from encuesta</select>

<select id="selectEncuestaById" parameterClass="int“ resultClass="Encuesta">select

codigo_encuesta as codigoEncuesta,descripcion_encuesta as descripcionEncuesta

from encuestawhere codigo_encuesta = #codigoEncuesta#

</select>

Page 9: iBatis course (beta)

El mapa de la clase Encuesta.java<!-- Insert example, using the Encuesta parameter class --><insert id="insertEncuesta" parameterClass="Encuesta">insert into encuesta (

descripcion_encuestavalues (

#descripcionEncuesta#)</insert>

<!-- Update example, using the Encuesta parameter class --><update id="updateEncuesta" parameterClass="Encuesta">update encuesta set

descripcion_encuesta = #descripcionEncuesta#where

codigo_encuesta = #codigoEncuesta#</update>

<!-- Delete example, using an integer as the parameter class --><delete id="deleteEncuestaById" parameterClass="int">delete from encuesta where codigo_encuesta = #codigoEncuesta#</delete>

</sqlMap>

Page 10: iBatis course (beta)

Test del bean Encuestatry { Reader reader = Resources.getResourceAsReader("test/SqlMapConfig.xml"); sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader); reader.close(); } catch (IOException e) { // Fail fast. throw new RuntimeException("Something bad happened while building the SqlMapClient

instance." + e, e);}

. . .

public static List selectAllAccounts () throws SQLException { return sqlMapper.queryForList("selectAllEncuestas", new ArrayList()); } public static Encuesta selectEncuestaById (int id) throws SQLException { return (Encuesta) sqlMapper.queryForObject("selectEncuestaById", id); } public static void insertEncuesta (Encuesta Encuesta) throws SQLException { sqlMapper.insert("insertEncuesta", Encuesta); } public static void updateEncuesta (Encuesta Encuesta) throws SQLException { sqlMapper.update("updateEncuesta", Encuesta); } public static void deleteEncuesta (int id) throws SQLException { sqlMapper.delete("deleteEncuesta", id); }

Page 11: iBatis course (beta)

Sentencias de mapas en iBatis

Page 12: iBatis course (beta)

Sentencias de mapas en iBatis

Page 13: iBatis course (beta)

El elemento <sql><sql id="select-order"> select * from order </sql><sql id="select-count">

select count(*) as value from order </sql><sql id="where-shipped-after-value">

<![CDATA[where shipDate > #value:DATE#]]>

</sql><select id="getOrderShippedAfter" resultClass="map">

<include refid="select-order" /><include refid="where-shipped-after-value" />

</select><select id="getOrderCountShippedAfter" resultClass="int">

<include refid="select-count" /><include refid="where-shipped-after-value" />

</select>

Page 14: iBatis course (beta)

How do I use LIKE in my WHERE clauses?”

<select id="getByLikeCity" resultClass="Account">selectaccountId,username,password,firstName,lastName,address1,address2,city,state,postalCode,countryfrom Accountwhere city like '%$value$%'</select>

Page 15: iBatis course (beta)

Dynamic result mapping example

<select id="getAccountRemapExample" remapResults="true"resultClass="java.util.HashMap">

select accountId, username,<dynamic>

<isEqual property="includePassword" compareValue="true">password, </isEqual>

</dynamic>firstName, lastName from Account

<dynamic prepend=" where "><isNotEmpty property="city">

city like #city# </isNotEmpty><isNotNull property="accountId" prepend=" and ">

AccountId = #accountId# </isNotNull>

</dynamic></select>

Page 16: iBatis course (beta)

Mapping parameters

Attribute <select id="getOrderShippedAfter"

resultClass="java.util.HashMap">

select *

from order

where shipDate > #value:DATE#

</select>

property

javaType

jdbcType

nullValue

mode

typeHandler

Page 17: iBatis course (beta)

Ejemplo

<select id="getOrderShippedAfter" resultClass="hashmap">

select *

from "order"

where shipDate > #value,jdbcType=DATE#

</select>

Page 18: iBatis course (beta)

iBATIS does not allow you to get a primitive result directly,

Integer count = (Integer)sqlMap.queryForObject("Account.getOrderCountByAccount",new Integer(1));

<selectid="getOrderCountByAccount"resultClass="java.lang.Integer" >select count(*) as valuefrom orderwhere accountId = #value#</select>

Page 19: iBatis course (beta)

public class PrimitiveResult {private int orderCount;public int getOrderCount() {

return orderCount;}public void setOrderCount(int orderCount) {

this.orderCount = orderCount;}

}

<resultMap id="primitiveResultMapExample“ class="PrimitiveResult"><result property="orderCount“ column="orderCount" />

</resultMap>

<select id="getPrimitiveById“ resultMap="primitiveResultMapExample">select count(*) as orderCountfrom orderwhere accountId = #accountId#

</select>

Page 20: iBatis course (beta)

JavaBean and Map results

Page 21: iBatis course (beta)

Executing nonquery statements

• The insert method• Object insert(String id, Object parameterObject) throws SQLException;

• The update method• int update(String id, Object parameterObject) throws SQLException;

• The delete method• int delete(String id, Object parameterObject) throws SQLException;

Page 22: iBatis course (beta)

Nonquery mapped statements

Page 23: iBatis course (beta)

Nonquery mapped statements

Page 24: iBatis course (beta)

Inserting dataUsing inline parameter mapping

<insert id="insertWithInlineInfo">insert into account (

accountId,username, password,memberSince,firstName, lastName,address1, address2,city, state, postalCode,country, version

) values (#accountId:NUMBER#,#username:VARCHAR#, #password:VARCHAR#,#memberSince:TIMESTAMP#,#firstName:VARCHAR#, #lastName:VARCHAR#,#address1:VARCHAR#, #address2:VARCHAR#,#city:VARCHAR#, #state:VARCHAR#, #postalCode:VARCHAR#,#country:VARCHAR#, #version:NUMBER#

)</insert>

Page 25: iBatis course (beta)

Inserting dataUsing inline parameter mapping

Account account = new Account();account.setAccountId(new Integer(9999));account.setUsername("inlineins");account.setPassword("poohbear");account.setFirstName("Inline");account.setLastName("Example");sqlMapClient.insert("Account.insertWithInlineInfo", account);

Page 26: iBatis course (beta)

Inserting dataUsing an external parameter map

<parameterMap id="fullParameterMapExample" class="Account"><parameter property="accountId" jdbcType="NUMBER" /><parameter property="username" jdbcType="VARCHAR" /><parameter property="password" jdbcType="VARCHAR" /><parameter property="memberSince" jdbcType="TIMESTAMP" /><parameter property="firstName" jdbcType="VARCHAR" /><parameter property="lastName" jdbcType="VARCHAR" /><parameter property="address1" jdbcType="VARCHAR" /><parameter property="address2" jdbcType="VARCHAR" /><parameter property="city" jdbcType="VARCHAR" /><parameter property="state" jdbcType="VARCHAR" /><parameter property="postalCode" jdbcType="VARCHAR" /><parameter property="country" jdbcType="VARCHAR" /><parameter property="version" jdbcType="NUMBER" />

</parameterMap>

Page 27: iBatis course (beta)

Inserting dataUsing an external parameter map

<insert id="insertWithExternalInfo" parameterMap="fullParameterMapExample">

insert into account (accountId,username, password,memberSincefirstName, lastName,address1, address2,city, state, postalCode,country, version

) values (?,?,?,?,?,?,?,?,?,?,?,?,?

)</insert>

Page 28: iBatis course (beta)

Autogenerated keys

Object insert( String id, Object parameterObject ) throws SQLException;

<insert id="insert">

<selectKey keyProperty="accountId“ resultClass="int">

SELECT nextVal('account_accountid_seq')

</selectKey>

INSERT INTO Account ( accountId, username, password

) VALUES(

#accountId#, #username#, #password# )

</insert>

Integer returnValue = (Integer) sqlMap.insert("Account.insert", account);

Page 29: iBatis course (beta)

Autogenerated keys

In SQL Server:

<insert id="insert">INSERT INTO Account (

username, password) VALUES(

#username#, #password#)<selectKeykeyProperty="accountId"resultClass="int">

SELECT SCOPE_IDENTITY()</selectKey>

</insert>

In MySQL:

<insert id="insert">INSERT INTO Account (

username, password) VALUES(

#username#, #password#)<selectKeykeyProperty="accountId"resultClass="int">

SELECT LAST_INSERT_ID( )</selectKey>

</insert>

Page 30: iBatis course (beta)

Updating or deleting child records

public void saveOrder(SqlMapClient sqlMapClient, Order order)throws SQLException {

if (null == order.getOrderId()) {sqlMapClient.insert("Order.insert", order);

} else {sqlMapClient.update("Order.update", order);

}sqlMapClient.delete("Order.deleteDetails", order);for (int i = 0; i < order.getOrderItems().size(); i++) {

OrderItem oi = (OrderItem) order.getOrderItems().get(i);oi.setOrderId(order.getOrderId());sqlMapClient.insert("OrderItem.insert", oi);

}}

Page 31: iBatis course (beta)

Running batch updatespublic void saveOrder(SqlMapClient sqlMapClient, Order order)throws SQLException {

sqlMapClient.startTransaction();try {

if (null == order.getOrderId()) {sqlMapClient.insert("Order.insert", order);

} else {sqlMapClient.update("Order.update", order);

}sqlMapClient.startBatch();sqlMapClient.delete("Order.deleteDetails", order);for (int i = 0; i < order.getOrderItems().size(); i++) {

OrderItem oi = (OrderItem) order.getOrderItems().get(i);oi.setOrderId(order.getOrderId());sqlMapClient.insert("OrderItem.insert", oi);

}sqlMapClient.executeBatch();sqlMapClient.commitTransaction();

} finally {sqlMapClient.endTransaction();

}}

Page 32: iBatis course (beta)

Working with stored procedures

CREATE OR REPLACE FUNCTION max_in_example(a float4, b float4)

RETURNS float4 AS$BODY$

BEGINif (a > b) then

return a;else

return b;end if;

END;$BODY$LANGUAGE 'plpgsql' VOLATILE;

Page 33: iBatis course (beta)

Working with stored procedures

// En el Mapping ML<parameterMap id="pm_in_example" class="java.util.Map">

<parameter property="a" /><parameter property="b" />

</parameterMap><procedure id="in_example" parameterMap="pm_in_example“ resultClass="int" >

{ call max_in_example(?, ?) }</procedure>

// EN JavaMap m = new HashMap(2);m.put("a", new Integer(7));m.put("b", new Integer(5));Integer val =

(Integer)sqlMap.queryForObject("Account.in_example", m);

Page 34: iBatis course (beta)

Working with stored procedures

create or replace procedure maximum

(a in integer, b in integer, c out integer) as

begin

if (a > b) then c := a; end if;

if (b >= a) then c := b; end if;

end;

Page 35: iBatis course (beta)

Working with stored procedures

<parameterMap id="maxOutProcedureMap" class="java.util.Map"><parameter property="a" mode="IN" /><parameter property="b" mode="IN" /><parameter property="c" mode="OUT" />

</parameterMap><procedure id="maxOutProcedure"

parameterMap="maxOutProcedureMap">{ call maximum (?, ?, ?) }

</procedure>

// Call maximum functionMap m = new HashMap(2);m.put("a", new Integer(7));m.put("b", new Integer(5));sqlMap.queryForObject("Account.maxOutProcedure", m);// m.get("c") should be 7 now.

Page 36: iBatis course (beta)

XML parameters<select id="getByXmlId" resultClass="Account" parameterClass="xml">

selectaccountId,username,password,firstName,lastName,address1,address2,city,state,postalCode,country

from Accountwhere accountId = #accountId#

</select>

String parameter = "<parameter><accountId>3</accountId></parameter>";

Account account = (Account) sqlMapClient.queryForObject(

"Account.getByXmlId", parameter);

Page 37: iBatis course (beta)

XML parameters<select id="getByDomId" resultClass="Account" parameterClass="dom">

selectaccountId,username,password,firstName,lastName,address1,address2,city,state,postalCode,country

from Accountwhere accountId = #accountId#

</select>

Document parameterDocument = DocumentBuilderFactory.newInstance()

.newDocumentBuilder().newDocument();Element paramElement = parameterDocument .createElement("parameterDocument");Element accountIdElement = parameterDocument .createElement("accountId");accountIdElement.setTextContent("3");paramElement.appendChild(accountIdElement);parameterDocument.appendChild(paramElement);

Account account = (Account) sqlMapClient.queryForObject(

"Account.getByXmlId", parameterDocument);

Page 38: iBatis course (beta)

XML results<select id="getByIdValueXml" resultClass="xml"xmlResultName="account">

selectaccountId,username,password

from Accountwhere accountId = #value#

</select>

String xmlData = (String) sqlMap.queryForObject("Account.getByIdValueXml", new Integer(1));

Page 39: iBatis course (beta)

XML resultsXML<select id="getByIdValueXml" resultClass="xml"xmlResultName="account">

selectaccountId,username,password

from Accountwhere accountId = #value#

</select>

JavaString xmlData = (String) sqlMap.queryForObject("Account.getByIdValueXml",

new Integer(1));

Return<?xml version="1.0" encoding="UTF-8"?><account><accountid>1</accountid><username>lmeadors</username><password>blah</password></account>

Page 40: iBatis course (beta)

XML parameters<select id="getAllXml" resultClass="xml" xmlResultName="account">select

accountId,username,password,firstName,lastName,address1,address2,city,state,postalCode,country

from Account</select>

List xmlList = sqlMap.queryForList("Account.getAllXml", null);

Page 41: iBatis course (beta)

Automatic transactionspublic void runStatementsUsingAutomaticTransactions() {

SqlMapClient sqlMapClient =SqlMapClientConfig.getSqlMapClient();Person p = (Person)sqlMapClient.queryForObject("getPerson", new Integer(9));p.setLastName("Smith");sqlMapClient.update("updatePerson", p);

}

Page 42: iBatis course (beta)

Local transactions

<transactionManager type="JDBC">

<dataSource type="SIMPLE">

<property …/>

<property …/>

<property …/>

</dataSource>

</transactionManager>

public void runStatementsUsingLocalTransactions() {SqlMapClient sqlMapClient =SqlMapClientConfig.getSqlMapClient();try {

sqlMapClient.startTransaction();Person p = (Person) sqlMapClient.queryForObject

("getPerson", new Integer(9));p.setLastName("Smith");sqlMapClient.update("updatePerson", p);

Department d = (Department) sqlMapClient.queryForObject("getDept", new Integer(3));

p.setDepartment(d);sqlMapClient.update("updatePersonDept", p);sqlMapClient.commitTransaction();

} finally {sqlMapClient.endTransaction();

}}

Page 43: iBatis course (beta)

Global transactions<!– Active participation <transactionManager type="JTA">

<property name="UserTransaction"value="java:/ctx/con/someUserTransaction"/>

<dataSource type="JNDI"><property name="DataSource"value="java:comp/env/jdbc/

someDataSource"/></dataSource>

</transactionManager>

<!– Pasive participation <transactionManager type="EXTERNAL">

<dataSource type="JNDI"><property name="DataSource"value="java:comp/env/jdbc/someDataSource"/></dataSource>

</transactionManager>

Page 44: iBatis course (beta)

Starting, committing, and ending the transaction

public void runStatementsUsingGlobalTransactions() {SqlMapClient sqlMapClient =

SqlMapClientConfig.getSqlMapClient();try {

sqlMapClient.startTransaction();Person p = (Person)sqlMapClient.queryForObject

("getPerson", new Integer(9));

p.setLastName("Smith");sqlMapClient.update("updatePerson", p);Department d = (Department)sqlMapClient.queryForObject

("getDept", new Integer(3));

p.setDepartment(d);sqlMapClient.update("updatePersonDept", p);sqlMapClient.commitTransaction();

} finally {sqlMapClient.endTransaction();

}}

Page 45: iBatis course (beta)

Custom transaction control with setUserTransaction()

public void runStatementsUsingSetUserConnection() {SqlMapClient sqlMapClient = SqlMapClientConfig.getSqlMapClient();Connection conn = null;try {

conn = dataSource.getConnection();conn.setAutoCommit(false);sqlMapClient.setUserConnection(conn);Person p = (Person)sqlMapClient.queryForObject ("getPerson", new Integer(9));p.setLastName("Smith");sqlMapClient.update("updatePerson", p);Department d = (Department)sqlMapClient.queryForObject

("getDept", new Integer(3));p.setDepartment(d);sqlMapClient.update("updatePersonDept", p);conn.commit();

} finally {sqlMapClient.setUserConnection(null);if (conn != null) conn.close();

}}

Page 46: iBatis course (beta)

Custom transaction control with openSession()

public void runStatementsUsingSetUserConnection() {SqlMapClient sqlMapClient = SqlMapClientConfig.getSqlMapClient();Connection conn = null;SqlMapSession session = null;try {

conn = dataSource.getConnection();conn.setAutoCommit(false);session = sqlMapClient.openSession(conn);Person p = (Person)session.queryForObject("getPerson", new Integer(9));

p.setLastName("Smith");session.update("updatePerson", p);Department d = (Department) session.queryForObject("getDept", new Integer(3));

p.setDepartment(d);session.update("updatePersonDept", p);conn.commit();

} finally {if (session != null) session.close();if (conn != null) conn.close();

}}

Page 47: iBatis course (beta)

The ideal plae for transactions is the business layer

Page 48: iBatis course (beta)

Example of Dynamic WHERE clause

…<select id="getChildCategories"

parameterClass="Category"resultClass="Category">

SELECT *FROM category<dynamic prepend="WHERE "><isNull property="parentCategoryId">

parentCategoryId IS NULL</isNull><isNotNull property="parentCategoryId">

parentCategoryId=#parentCategoryId#</isNotNull></dynamic>

</select>…

Page 49: iBatis course (beta)

Mock removeFirstPrepend example

…<dynamic prepend="WHERE ">…

<isNotEmpty property="y">y=#y#

</isNotEmpty><isNotNull property="x" removeFirstPrepend="true"prepend="AND" open="(" close=")"><isNotEmpty property="x.a" prepend="OR">

a=#x.a#</isNotEmpty><isNotEmpty property="x.b" prepend="OR">

a=#x.b#</isNotEmpty><isNotEmpty property="x.c" prepend="OR">

a=#x.c#</isNotEmpty></isNotNull>

…</dynamic>…

Page 50: iBatis course (beta)

The <dynamic> tag

Page 51: iBatis course (beta)
Page 52: iBatis course (beta)

iBATIS binary dynamic tags

Page 53: iBatis course (beta)

Binary tag example…<select id="getShippingType" parameterClass="Cart"

resultClass="Shipping">SELECT * FROM Shipping

<dynamic prepend="WHERE "><isGreaterEqual property="weight" compareValue="100">shippingType='FREIGHT'

</isEqual><isLessThan property="weight" compareValue="100">shippingType='STANDARD'

</isLessThan></dynamic>

</select>…

Page 54: iBatis course (beta)

Unary tags

Page 55: iBatis course (beta)

Unary tags

Page 56: iBatis course (beta)

Unary tag example

<select id="getProducts" parameterClass="Product"

resultClass="Product">

SELECT * FROM Products

<dynamic prepend="WHERE ">

<isNotEmpty property="productType">

productType=#productType#

</isNotEmpty>

</dynamic>

</select>

Page 57: iBatis course (beta)

Parameter tags

Page 58: iBatis course (beta)

Parameter tag example

<select id="getProducts" resultClass="Product">

SELECT * FROM Products

<isParameterPresent prepend="WHERE ">

<isNotEmpty property="productType">

productType=#productType#

</isNotEmpty>

</ isParameterPresent >

</select>

Page 59: iBatis course (beta)

The <iterate> tag

Page 60: iBatis course (beta)

<iterate> tag example

<select id="getProducts" parameterClass="Product"

resultClass="Product">

SELECT * FROM Products

<dynamic prepend="WHERE productType IN ">

<iterate property="productTypes“ open="(" close=")"

conjunction=",">

productType=#productType#

</iterate>

</dynamic>

</select>

Page 61: iBatis course (beta)

A simple iBATIS caching example

<cacheModel id="categoryCache" type="MEMORY"><flushOnExecute statement="insert"/><flushOnExecute statement="update"/><flushOnExecute statement="delete"/><property name="reference-type" value="WEAK"/>

</cacheModel>

<selectid="getCategory" parameterClass="Category"resultClass="Category" cacheModel="categoryCache">SELECT *FROM CategoryWHERE categoryId=#categoryId#

</select>

Page 62: iBatis course (beta)

Understanding the cache model

Page 63: iBatis course (beta)

Built-in cache model types

Page 64: iBatis course (beta)

The readOnly attributeThe <cacheModel> tag provides a readOnly attribute. This attribute is

simply an indicator that provides instruction to the cache model, telling it how it should retrieve and store the cached object.

Setting this attribute to true does not prevent retrieved objects from having their contents altered. When specifying a cache as read only, you tell the cache model that it is allowed to pass back a reference to the object that exists in the cache because it is not going to be altered by the application that is requesting it.

If the readOnly attribute is set to false, this ensures that more than one user does not retrieve the same instance of a cached reference.

The readOnly attribute works in conjunction with the serialize attribute. It is important to understand how these two attributes work together.

Page 65: iBatis course (beta)

The serialize attribute

The serialize attribute is used to instruct how cached objects are returned.

When serialize is set to true, each object requested from the cache is returned as a deep copy. This means that the object you retrieve from the cache will have an identical value but will not be the same instance. This ensures that the actual version that is stored in the cache is never returned.

It is important to call attention to the fact that this is not serialization as most would think of it. The objects do not get serialized to disk. This is memory-based serialization that creates deep copies of the cached objects that are in memory.

Page 66: iBatis course (beta)

Summary of readOnly and serialize attribute combinations

Page 67: iBatis course (beta)

Cache flushing

Page 68: iBatis course (beta)

flushOnExecute caching example<sqlMap namespace="Category">…<cacheModel id="categoryCache" type="MEMORY">

…<flushOnExecute statement="Category.insert"/>…

</cacheModel>…<select id="getCategory" parameterClass="Category"

resultClass="Category" cacheModel="categoryCache">SELECT *FROM CategoryWHERE parentCategoryId=#categoryId#

</select>…<insert id="insert" parameterClass="Category" >

INSERT INTO Category(title, description, sequence)VALUES(#title#,#description#,#sequence#)

</insert>…</sqlMap>

Page 69: iBatis course (beta)

<flushInterval>

Page 70: iBatis course (beta)

<flushInterval> caching example<sqlMap namespace="Category">

…<cacheModel id="categoryCache" type="MEMORY">…<flushInterval hours= "12" />…

</cacheModel>…<select id="getCategory" parameterClass="Category"

resultClass="Category" cacheModel="categoryCache">SELECT *

FROM CategoryWHERE parentCategoryId=#categoryId#

</select>…</sqlMap>

Page 71: iBatis course (beta)

Cache model types

• MEMORY

• LRU

• FIFO

• OSCACHE

Page 72: iBatis course (beta)

MEMORY

Page 73: iBatis course (beta)

Sample MEMORY cacheModel

<cacheModel id="categoryCache" type="MEMORY"><flushInterval hours="24"/>

<flushOnExecute statement="insert"/>

<flushOnExecute statement="update"/>

<flushOnExecute statement="delete"/>

<property name="reference-type" value="WEAK"/>

</cacheModel>

Page 74: iBatis course (beta)

LRU

<cacheModel id="categoryCache" type="LRU"><flushInterval hours="24"/><flushOnExecute statement="insert"/><flushOnExecute statement="update"/><flushOnExecute statement="delete"/><property name="size" value="200"/>

</cacheModel>

Page 75: iBatis course (beta)

FIFO

<cacheModel id="categoryCache" type="FIFO"><flushInterval hours="24"/><flushOnExecute statement="insert"/><flushOnExecute statement="update"/><flushOnExecute statement="delete"/><property name="size" value="1000"/>

</cacheModel>

Page 76: iBatis course (beta)

<cacheModel id="categoryCache" type="OSCACHE"><flushInterval hours="24"/>

<flushOnExecute statement="insert"/>

<flushOnExecute statement="update"/>

<flushOnExecute statement="delete"/>

</cacheModel>

www.opensymphony.com/oscache/

www.opensymphony.com/oscache/documentation

Page 77: iBatis course (beta)

Caching read-only, long-term data<cacheModel id="categoryCache" type="LRU">

<flushInterval hours="24"/><flushOnExecute statement="insert"/><flushOnExecute statement="update"/><flushOnExecute statement="delete"/><property name="size" value="50"/>

</cacheModel>

<select id="getChildCategories" parameterClass="Category"resultClass="Category" cacheModel="categoryCache">SELECT * FROM category<dynamic prepend="WHERE ">

<isNull property="categoryId">parentCategoryId IS NULL

</isNull><isNotNull property="categoryId">

parentCategoryId=#categoryId:INTEGER:0#</isNotNull>

</dynamic>ORDER BY sequence, title

</select>

Page 78: iBatis course (beta)

Caching read-write data

<cacheModel id="productCache" type="MEMORY"readOnly="true" serialize="false"><flushOnExecute statement="Product.add" /><flushOnExecute statement="Product.edit" /><flushOnExecute statement="Product.remove" /><property name="reference-type" value="WEAK" />

</cacheModel>

<select id="getProductById" resultClass="Product"parameterClass="Product" cacheModel="productCache">SELECT * FROM Product WHERE productId=#productId#

</select>

Page 79: iBatis course (beta)

Caching aging static data<cacheModel id="hotProductCache" type="FIFO">

<flushOnExecute statement="Product.update"/><flushOnExecute statement="Product.delete"/><property name="size" value="12"/>

</cacheModel>

<select id="getPopularProductsByPurchaseDate“ parameterClass="Product“ resultClass="Product" cacheModel="hotProductsCache">SELECT count(productId) countNum, productIdFROM productPurchaseWHEREpurchaseDate BETWEEN#startDate# AND #endDate#GROUP BY productIdORDER BY countNum DESCLIMIT 5

</select>