ibatis course (beta)

Post on 16-May-2015

3.944 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

iBatis course (beta)

TRANSCRIPT

Curso de iBatis

For smarties

Instalando iBatis

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

Archivos:• ibatis-2.3.4.726.zip

• Unziped• ibatis-2.3.4.726.jar

Configurando iBatis

Configurando iBatis

1. Crear el SqlMapConfig.xml

2. Crear el db.properties

3. Crear la clase java

4. Crear el mapping para esa clase

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>

El db.properties

driver=com.mysql.jdbc.Driver

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

user=root

pword=mysql

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;}

}

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>

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>

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); }

Sentencias de mapas en iBatis

Sentencias de mapas en iBatis

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>

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>

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>

Mapping parameters

Attribute <select id="getOrderShippedAfter"

resultClass="java.util.HashMap">

select *

from order

where shipDate > #value:DATE#

</select>

property

javaType

jdbcType

nullValue

mode

typeHandler

Ejemplo

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

select *

from "order"

where shipDate > #value,jdbcType=DATE#

</select>

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>

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>

JavaBean and Map results

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;

Nonquery mapped statements

Nonquery mapped statements

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>

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);

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>

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>

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);

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>

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);

}}

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();

}}

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;

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);

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;

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.

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);

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);

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));

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>

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);

Automatic transactionspublic void runStatementsUsingAutomaticTransactions() {

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

}

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();

}}

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>

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();

}}

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();

}}

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();

}}

The ideal plae for transactions is the business layer

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

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

The <dynamic> tag

iBATIS binary dynamic tags

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

Unary tags

Unary tags

Unary tag example

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

resultClass="Product">

SELECT * FROM Products

<dynamic prepend="WHERE ">

<isNotEmpty property="productType">

productType=#productType#

</isNotEmpty>

</dynamic>

</select>

Parameter tags

Parameter tag example

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

SELECT * FROM Products

<isParameterPresent prepend="WHERE ">

<isNotEmpty property="productType">

productType=#productType#

</isNotEmpty>

</ isParameterPresent >

</select>

The <iterate> tag

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

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>

Understanding the cache model

Built-in cache model types

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.

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.

Summary of readOnly and serialize attribute combinations

Cache flushing

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>

<flushInterval>

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

Cache model types

• MEMORY

• LRU

• FIFO

• OSCACHE

MEMORY

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>

LRU

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

</cacheModel>

FIFO

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

</cacheModel>

<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

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>

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>

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>

top related