SlideShare a Scribd company logo
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 Crear el SqlMapConfig.xml Crear el db.properties Crear la clase java Crear el mapping para esa clase
El SqlMapConfig.xml <? xml   version = &quot;1.0&quot;   encoding = &quot;UTF-8&quot; ?> <! DOCTYPE   sqlMapConfig PUBLIC   &quot;-//ibatis.apache.org//DTD SQL Map Config 2.0//EN&quot; &quot;http://ibatis.apache.org/dtd/sql-map-config-2.dtd&quot; > < sqlMapConfig > < properties   resource = &quot;db.properties&quot;   /> < settings   useStatementNamespaces = &quot;false&quot;   cacheModelsEnabled = &quot;true&quot;   enhancementEnabled = &quot;true&quot;     lazyLoadingEnabled = &quot;true&quot;     maxRequests = &quot;32&quot; maxSessions = &quot;10&quot;   maxTransactions = &quot;5&quot;   /> < transactionManager   type = &quot;JDBC&quot; > < dataSource   type = &quot;SIMPLE&quot; > < property   name = &quot;JDBC.Driver&quot;   value = &quot;${driver}&quot;   /> < property   name = &quot;JDBC.ConnectionURL&quot;   value = &quot;${url}&quot;   /> < property   name = &quot;JDBC.Username&quot;   value = &quot;${user}&quot;   /> < property   name = &quot;JDBC.Password&quot;   value = &quot;${pword}&quot;   /> </ dataSource > </ transactionManager > < sqlMap   resource = &quot;test/Encuesta.xml&quot;   /> </ sqlMapConfig >
El db.properties driver= com . mysql . jdbc .Driver url=jdbc:mysql:// localhost :3306/ encuesta user=root pword= mysql
La clase Encuesta.java package  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 = &quot;1.0&quot;   encoding = &quot;UTF-8&quot;   ?> <! DOCTYPE   sqlMap   PUBLIC   &quot;-//ibatis.apache.org//DTD SQL Map 2.0//EN&quot;   &quot;http://ibatis.apache.org/dtd/sql-map-2.dtd&quot; > < sqlMap   namespace = &quot;Encuesta&quot; > <!-- Use type aliases to avoid typing the full  classname  every time. --> < typeAlias   alias = &quot;Encuesta&quot;   type = &quot;enitity.Encuesta&quot;   /> < resultMap   id = &quot; EncuestaResult &quot;   class = &quot;Encuesta&quot; > < result   property = &quot; codigoEncuesta &quot;   column = &quot; codigo_encuesta &quot;   /> < result   property = &quot; descripcionEncuesta &quot;   column = &quot; descripcion_encuesta &quot;   /> </ resultMap > <!-- Select with no parameters using the result map for  Encuesta  class. --> < select   id = &quot; selectAllEncuestas &quot;   resultMap = &quot;EncuestaResult&quot; > select * from  encuesta </ select > < select   id = &quot; selectEncuestaById &quot;   parameterClass = &quot;int“  resultClass = &quot;Encuesta&quot; > select codigo_encuesta as codigoEncuesta, descripcion_encuesta as descripcionEncuesta from  encuesta where codigo_encuesta = #codigoEncuesta# </ select >
El mapa de la clase Encuesta.java <!-- Insert example, using the  Encuesta  parameter class --> < insert   id = &quot; insertEncuesta &quot;   parameterClass = &quot;Encuesta&quot; > insert into  encuesta  ( descripcion_encuesta values ( #descripcionEncuesta# ) </ insert > <!-- Update example, using the  Encuesta  parameter class --> < update   id = &quot; updateEncuesta &quot;   parameterClass = &quot;Encuesta&quot; > update  encuesta  set descripcion_encuesta = #descripcionEncuesta# where codigo_encuesta = #codigoEncuesta# </ update > <!-- Delete example, using an integer as the parameter class --> < delete   id = &quot; deleteEncuestaById &quot;   parameterClass = &quot;int&quot; > delete from  encuesta  where codigo_encuesta = #codigoEncuesta# </ delete > </ sqlMap >
Test del bean Encuesta try  { Reader reader = Resources. getResourceAsReader ( &quot;test/SqlMapConfig.xml&quot; ); sqlMapper  = SqlMapClientBuilder. buildSqlMapClient (reader); reader.close();  }  catch  (IOException e) { // Fail fast. throw   new  RuntimeException( &quot;Something bad happened while building the SqlMapClient instance.&quot;  + e, e); } . . . public   static   List  selectAllAccounts ()  throws  SQLException { return   sqlMapper .queryForList ( &quot;selectAllEncuestas&quot; ,  new   ArrayList ()); } public   static  Encuesta selectEncuestaById  ( int  id)  throws  SQLException { return  (Encuesta)  sqlMapper .queryForObject ( &quot;selectEncuestaById&quot; , id); } public   static   void  insertEncuesta (Encuesta Encuesta)  throws  SQLException { sqlMapper .insert ( &quot;insertEncuesta&quot; , Encuesta); } public   static   void  updateEncuesta (Encuesta Encuesta)  throws  SQLException { sqlMapper .update ( &quot;updateEncuesta&quot; , Encuesta); } public   static   void  deleteEncuesta ( int  id)  throws  SQLException { sqlMapper .delete ( &quot;deleteEncuesta&quot; , id); }
Sentencias de mapas en iBatis
Sentencias de mapas en iBatis
El elemento <sql> < sql   id = &quot;select-order&quot; >   select * from order   </ sql > < sql   id = &quot;select-count&quot; > select count(*) as value from order   </ sql > < sql   id = &quot;where-shipped-after-value&quot; > <![CDATA[ where shipDate > #value:DATE# ]]> </ sql > < select   id = &quot;getOrderShippedAfter&quot;   resultClass = &quot;map&quot; > < include   refid = &quot; select-order &quot;   /> < include   refid = &quot; where-shipped-after-value &quot;   /> </ select > < select   id = &quot;getOrderCountShippedAfter&quot;   resultClass = &quot;int&quot; > < include   refid = &quot; select-count &quot;   /> < include   refid = &quot; where-shipped-after-value &quot;   /> </ select >
How do I use LIKE in my WHERE clauses?” < select   id = &quot;getByLikeCity&quot;   resultClass = &quot;Account&quot; > select accountId, username , password, firstName, lastName, address1, address2, city, state, postalCode, country from Account where city like  '%$value$%' </ select >
Dynamic result mapping example < select   id = &quot;getAccountRemapExample&quot;   remapResults = &quot;true&quot; resultClass = &quot;java.util.HashMap&quot; > select accountId,  username , < dynamic > < isEqual   property = &quot;includePassword&quot;   compareValue = &quot;true&quot; > password,  </ isEqual > </ dynamic > firstName, lastName from Account < dynamic   prepend = &quot; where &quot; > < isNotEmpty   property = &quot;city&quot; > city like #city#  </ isNotEmpty > < isNotNull   property = &quot;accountId&quot;   prepend = &quot; and &quot; > AccountId = #accountId#  </ isNotNull > </ dynamic > </ select >
Mapping parameters mode  typeHandler nullValue jdbcType javaType property Attribute <select id=&quot;getOrderShippedAfter&quot; resultClass=&quot;java.util.HashMap&quot;> select * from order where shipDate > #value:DATE# </select>
Ejemplo < select   id = &quot;getOrderShippedAfter&quot;   resultClass = &quot;hashmap&quot; >   select *  from &quot;order&quot;  where shipDate >  #value,jdbcType=DATE#   </ select >
iBATIS does not allow you to get a primitive result directly, Integer count = (Integer)sqlMap.queryForObject( &quot;Account.getOrderCountByAccount&quot;, new Integer(1)); <select id=&quot;getOrderCountByAccount&quot; resultClass=&quot; java.lang.Integer &quot; > select count(*) as value from order where accountId = #value# </select>
public class PrimitiveResult { private int orderCount; public int getOrderCount() { return orderCount; } public void setOrderCount(int orderCount) { this.orderCount = orderCount; } } <resultMap id=&quot;primitiveResultMapExample“ class=&quot;PrimitiveResult&quot;> <result property=&quot;orderCount“ column=&quot;orderCount&quot; /> </resultMap> <select id=&quot;getPrimitiveById“ resultMap=&quot;primitiveResultMapExample&quot;> select count(*) as orderCount from order where 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 data Using inline parameter mapping < insert   id = &quot;insertWithInlineInfo&quot; > 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 data Using inline parameter mapping Account account = new Account(); account.setAccountId(new Integer(9999)); account.setUsername(&quot; inlineins &quot;); account.setPassword(&quot; poohbear &quot;); account.setFirstName(&quot; Inline &quot;); account.setLastName(&quot; Example &quot;); sqlMapClient.insert(&quot; Account.insertWithInlineInfo &quot;, account);
Inserting data Using an external parameter map < parameterMap   id = &quot;fullParameterMapExample&quot;   class = &quot;Account&quot; > < parameter   property = &quot;accountId&quot;   jdbcType = &quot;NUMBER&quot;   /> < parameter   property = &quot;username&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;password&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;memberSince&quot;   jdbcType = &quot;TIMESTAMP&quot;   /> < parameter   property = &quot;firstName&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;lastName&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;address1&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;address2&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;city&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;state&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;postalCode&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;country&quot;   jdbcType = &quot;VARCHAR&quot;   /> < parameter   property = &quot;version&quot;   jdbcType = &quot;NUMBER&quot;   /> </ parameterMap >
Inserting data Using an external parameter map < insert   id = &quot;insertWithExternalInfo&quot;   parameterMap = &quot;fullParameterMapExample&quot; > insert into account ( accountId, username , password, memberSince firstName, lastName, address1, address2, city, state, postalCode, country, version ) values ( ?,?,?,?,?,?,?,?,?,?,?,?,? ) </ insert >
Autogenerated keys Object insert( String id, Object parameterObject ) throws SQLException; <insert id=&quot;insert&quot;> <selectKey keyProperty=&quot;accountId“ resultClass=&quot;int&quot;> SELECT nextVal('account_accountid_seq') </selectKey> INSERT INTO Account ( accountId, username, password ) VALUES( #accountId#, #username#, #password# ) </insert> Integer returnValue = (Integer) sqlMap.insert(&quot;Account.insert&quot;, account);
Autogenerated keys In SQL Server: <insert id=&quot;insert&quot;> INSERT INTO Account ( username, password ) VALUES( #username#, #password#) <selectKey keyProperty=&quot;accountId&quot; resultClass=&quot;int&quot;> SELECT SCOPE_IDENTITY() </selectKey> </insert> In MySQL: <insert id=&quot;insert&quot;> INSERT INTO Account ( username, password ) VALUES( #username#, #password#) <selectKey keyProperty=&quot;accountId&quot; resultClass=&quot;int&quot;> 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( &quot;Order.insert&quot; , order); }  else  { sqlMapClient.update( &quot;Order.update&quot; , order); } sqlMapClient.delete( &quot;Order.deleteDetails&quot; , order); for  ( int  i = 0; i < order.getOrderItems().size(); i++) { OrderItem oi = (OrderItem) order.getOrderItems().get(i); oi.setOrderId(order.getOrderId()); sqlMapClient.insert( &quot;OrderItem.insert&quot; , oi); } }
Running batch updates public   void  saveOrder( SqlMapClient  sqlMapClient,  Order  order) throws   SQLException  { sqlMapClient.startTransaction(); try  { if  ( null  == order.getOrderId()) { sqlMapClient.insert( &quot;Order.insert&quot; , order); }  else  { sqlMapClient.update( &quot;Order.update&quot; , order); } sqlMapClient.startBatch(); sqlMapClient.delete( &quot;Order.deleteDetails&quot; , order); for  ( int  i = 0; i < order.getOrderItems().size(); i++) { OrderItem  oi = ( OrderItem ) order.getOrderItems().get(i); oi.setOrderId(order.getOrderId()); sqlMapClient.insert( &quot;OrderItem.insert&quot; , 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$ BEGIN if (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=&quot;pm_in_example&quot; class=&quot;java.util.Map&quot;> <parameter property=&quot;a&quot; /> <parameter property=&quot;b&quot; /> </parameterMap> <procedure id=&quot;in_example&quot; parameterMap=&quot;pm_in_example“ resultClass=&quot;int&quot; > { call max_in_example(?, ?) } </procedure> // EN Java Map m = new HashMap(2); m.put(&quot;a&quot;, new Integer(7)); m.put(&quot;b&quot;, new Integer(5)); Integer val = (Integer)sqlMap.queryForObject(&quot;Account.in_example&quot;, 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=&quot;maxOutProcedureMap&quot; class=&quot;java.util.Map&quot;> <parameter property=&quot;a&quot; mode=&quot;IN&quot; /> <parameter property=&quot;b&quot; mode=&quot;IN&quot; /> <parameter property=&quot;c&quot; mode=&quot;OUT&quot; /> </parameterMap> <procedure id=&quot;maxOutProcedure&quot; parameterMap=&quot;maxOutProcedureMap&quot;> {  call maximum (?, ?, ?) } </procedure> // Call maximum function Map m = new HashMap(2); m.put(&quot;a&quot;, new Integer(7)); m.put(&quot;b&quot;, new Integer(5)); sqlMap.queryForObject(&quot;Account.maxOutProcedure&quot;, m); // m.get(&quot;c&quot;) should be 7 now.
XML parameters < select   id = &quot;getByXmlId&quot;   resultClass = &quot;Account&quot;   parameterClass = &quot;xml&quot; > select accountId, username , password, firstName, lastName, address1, address2, city, state, postalCode, country from Account where accountId = #accountId# </ select > String  parameter  =  &quot;<parameter><accountId>3</accountId></parameter>&quot; ; Account  account = ( Account )  sqlMapClient .queryForObject( &quot;Account.getByXmlId&quot; , parameter) ;
XML parameters < select   id = &quot;getByDomId&quot;   resultClass = &quot;Account&quot;   parameterClass = &quot;dom&quot; > select accountId, username , password, firstName, lastName, address1, address2, city, state, postalCode, country from Account where accountId = #accountId# </ select > Document   parameterDocument  =  DocumentBuilderFactory .newInstance() .newDocumentBuilder().newDocument(); Element   paramElement  =  parameterDocument .createElement( &quot;parameterDocument&quot; ); Element   accountIdElement  =  parameterDocument .createElement( &quot;accountId&quot; ); accountIdElement . setTextContent( &quot;3&quot; ); paramElement . appendChild( accountIdElement ); parameterDocument . appendChild( paramElement ); Account  account  = ( Account )  sqlMapClient .queryForObject( &quot;Account.getByXmlId&quot; ,  parameterDocument );
XML results <select id=&quot; getByIdValueXml &quot; resultClass=&quot; xml &quot; xmlResultName=&quot; account &quot;> select accountId, username, password from Account where accountId = #value# </select> String xmlData = (String) sqlMap.queryForObject(&quot; Account.getByIdValueXml &quot;, new Integer(1));
XML results XML <select id=&quot; getByIdValueXml &quot; resultClass=&quot; xml &quot; xmlResultName=&quot; account &quot;> select accountId, username, password from Account where accountId = #value# </select> Java String xmlData = (String) sqlMap.queryForObject(&quot; Account.getByIdValueXml &quot;, new Integer(1)); Return <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <account> <accountid>1</accountid> <username>lmeadors</username> <password>blah</password> </account>
XML parameters <select id=&quot; getAllXml &quot; resultClass=&quot; xml &quot; xmlResultName=&quot; account &quot;> select accountId, username, password, firstName, lastName, address1, address2, city, state, postalCode, country from Account </select> List xmlList = sqlMap.queryForList(&quot; Account.getAllXml &quot;, null);
Automatic transactions public void runStatementsUsingAutomaticTransactions() { SqlMapClient sqlMapClient = SqlMapClientConfig.getSqlMapClient(); Person p = (Person) sqlMapClient.queryForObject(&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot; Smith &quot;); sqlMapClient.update(&quot; updatePerson &quot;, p); }
Local transactions <transactionManager  type=&quot;JDBC &quot;> <dataSource type=&quot;SIMPLE&quot;> <property …/> <property …/> <property …/> </dataSource> </transactionManager> public void runStatementsUsingLocalTransactions() { SqlMapClient sqlMapClient = SqlMapClientConfig.getSqlMapClient(); try { sqlMapClient.startTransaction(); Person p = (Person) sqlMapClient.queryForObject (&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot; Smith &quot;); sqlMapClient.update(&quot;updatePerson&quot;, p); Department d = (Department) sqlMapClient.queryForObject (&quot; getDept &quot;, new Integer(3)); p.setDepartment(d); sqlMapClient.update(&quot; updatePersonDept &quot;, p); sqlMapClient.commitTransaction(); } finally { sqlMapClient.endTransaction(); } }
Global transactions <!– Active participation   <transactionManager type=&quot; JTA &quot;> <property name=&quot; UserTransaction &quot; value=&quot; java:/ctx/con/someUserTransaction &quot;/> <dataSource type=&quot; JNDI &quot;> <property name=&quot; DataSource &quot; value=&quot; java:comp/env/jdbc/someDataSource &quot;/> </dataSource> </transactionManager> <!– Pasive participation   <transactionManager type=&quot; EXTERNAL &quot;> <dataSource type=&quot; JNDI &quot;> <property name=&quot; DataSource &quot; value=&quot; java:comp/env/jdbc/someDataSource &quot;/> </dataSource> </transactionManager>
Starting, committing, and ending the transaction public void runStatementsUsingGlobalTransactions() { SqlMapClient sqlMapClient = SqlMapClientConfig.getSqlMapClient(); try { sqlMapClient.startTransaction(); Person p = (Person)sqlMapClient.queryForObject (&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot;Smith&quot;); sqlMapClient.update(&quot;updatePerson&quot;, p); Department d = (Department)sqlMapClient.queryForObject (&quot; getDept &quot;, new Integer(3)); p.setDepartment(d); sqlMapClient.update(&quot; updatePersonDept &quot;, 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 (&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot; Smith &quot;); sqlMapClient.update(&quot; updatePerson &quot;, p); Department d = (Department)sqlMapClient.queryForObject (&quot; getDept &quot;, new Integer(3)); p.setDepartment(d); sqlMapClient.update(&quot; updatePersonDept &quot;, 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(&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot; Smith &quot;); session .update(&quot; updatePerson &quot;, p); Department d = (Department)  session .queryForObject(&quot; getDept &quot;, new Integer(3)); p.setDepartment(d); session .update(&quot; updatePersonDept &quot;, 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=&quot; getChildCategories &quot; parameterClass=&quot;Category&quot; resultClass=&quot; Category &quot;> SELECT * FROM category <dynamic prepend=&quot; WHERE  &quot;> <isNull property=&quot; parentCategoryId &quot;> parentCategoryId IS NULL </isNull> <isNotNull property=&quot; parentCategoryId &quot;> parentCategoryId=# parentCategoryId # </isNotNull> </dynamic> </select> …
Mock removeFirstPrepend example … <dynamic prepend=&quot;WHERE &quot;> … <isNotEmpty property=&quot;y&quot;> y=#y# </isNotEmpty> <isNotNull property=&quot;x&quot; removeFirstPrepend=&quot;true&quot; prepend=&quot;AND&quot; open=&quot;(&quot; close=&quot;)&quot;> <isNotEmpty property=&quot;x.a&quot; prepend=&quot;OR&quot;> a=#x.a# </isNotEmpty> <isNotEmpty property=&quot;x.b&quot; prepend=&quot;OR&quot;> a=#x.b# </isNotEmpty> <isNotEmpty property=&quot;x.c&quot; prepend=&quot;OR&quot;> a=#x.c# </isNotEmpty> </isNotNull> … </dynamic> …
The <dynamic> tag
 
iBATIS binary dynamic tags
Binary tag example … <select id=&quot;getShippingType&quot; parameterClass=&quot;Cart&quot; resultClass=&quot;Shipping&quot;> SELECT * FROM Shipping <dynamic prepend=&quot; WHERE  &quot;> <isGreaterEqual property=&quot; weight &quot; compareValue=&quot;100&quot;> shippingType= 'FREIGHT ' </isEqual> <isLessThan property=&quot; weight &quot; compareValue=&quot;100&quot;> shippingType= 'STANDARD ' </isLessThan> </dynamic> </select> …
Unary tags
Unary tags
Unary tag example … <select id=&quot; getProducts &quot; parameterClass=&quot; Product &quot; resultClass=&quot; Product &quot;> SELECT * FROM Products <dynamic prepend=&quot; WHERE  &quot;> <isNotEmpty property=&quot; productType &quot;> productType=#productType# </isNotEmpty> </dynamic> </select> …
Parameter tags
Parameter tag example … <select id=&quot;getProducts&quot; resultClass=&quot;Product&quot;> SELECT * FROM Products <isParameterPresent prepend=&quot;WHERE &quot;> <isNotEmpty property=&quot;productType&quot;> productType=#productType# </isNotEmpty> </ isParameterPresent > </select> …
The <iterate> tag
<iterate> tag example … <select id=&quot; getProducts &quot; parameterClass=&quot; Product &quot; resultClass=&quot; Product &quot;> SELECT * FROM Products <dynamic prepend=&quot; WHERE productType IN  &quot;> <iterate property=&quot; productTypes “ open =&quot;(&quot;  close=&quot; ) &quot; conjunction=&quot; ,&quot; > productType=#productType# </iterate> </dynamic> </select> …
A simple iBATIS caching example <cacheModel id=&quot; categoryCache &quot; type=&quot; MEMORY &quot;> <flushOnExecute statement=&quot; insert &quot;/> <flushOnExecute statement=&quot; update &quot;/> <flushOnExecute statement=&quot; delete &quot;/> <property name=&quot; reference-type &quot; value=&quot; WEAK &quot;/> </cacheModel> <select id=&quot; getCategory &quot; parameterClass=&quot; Category &quot; resultClass=&quot; Category &quot; cacheModel=&quot; categoryCache &quot;> SELECT * FROM Category WHERE categoryId=#categoryId# </select>
Understanding the cache model
Built-in cache model types
The readOnly attribute The <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=&quot; Category &quot;> … <cacheModel id=&quot; categoryCache &quot; type=&quot; MEMORY &quot;> … <flushOnExecute statement=&quot; Category.insert &quot;/> … </cacheModel> … <select id=&quot; getCategory &quot; parameterClass=&quot; Category &quot; resultClass=&quot; Category &quot; cacheModel=&quot; categoryCache &quot;> SELECT * FROM Category WHERE parentCategoryId=#categoryId# </select> … <insert id=&quot; insert &quot; parameterClass=&quot; Category &quot; > INSERT INTO Category (title, description, sequence) VALUES (#title#,#description#,#sequence#) </insert> … </sqlMap>
<flushInterval>
<flushInterval> caching example <sqlMap namespace=&quot; Category &quot;> … <cacheModel id=&quot; categoryCache &quot; type=&quot; MEMORY &quot;> … <flushInterval hours= &quot; 12 &quot; /> … </cacheModel> … <select id=&quot; getCategory &quot; parameterClass=&quot; Category &quot; resultClass=&quot; Category &quot; cacheModel=&quot; categoryCache &quot;> SELECT * FROM Category WHERE parentCategoryId=#categoryId# </select> … </sqlMap>
Cache model types MEMORY LRU FIFO OSCACHE
MEMORY
Sample MEMORY cacheModel <cacheModel id=&quot;categoryCache&quot; type=&quot;MEMORY&quot;> <flushInterval hours=&quot;24&quot;/> <flushOnExecute statement=&quot;insert&quot;/> <flushOnExecute statement=&quot;update&quot;/> <flushOnExecute statement=&quot;delete&quot;/> <property name=&quot;reference-type&quot; value=&quot;WEAK&quot;/> </cacheModel>
LRU <cacheModel id=&quot;categoryCache&quot; type=&quot;LRU&quot;> <flushInterval hours=&quot;24&quot;/> <flushOnExecute statement=&quot;insert&quot;/> <flushOnExecute statement=&quot;update&quot;/> <flushOnExecute statement=&quot;delete&quot;/> <property name=&quot;size&quot; value=&quot;200&quot;/> </cacheModel>
FIFO <cacheModel id=&quot;categoryCache&quot; type=&quot;FIFO&quot;> <flushInterval hours=&quot;24&quot;/> <flushOnExecute statement=&quot;insert&quot;/> <flushOnExecute statement=&quot;update&quot;/> <flushOnExecute statement=&quot;delete&quot;/> <property name=&quot;size&quot; value=&quot;1000&quot;/> </cacheModel>
<cacheModel id=&quot;categoryCache&quot; type=&quot;OSCACHE&quot;> <flushInterval hours=&quot;24&quot;/> <flushOnExecute statement=&quot;insert&quot;/> <flushOnExecute statement=&quot;update&quot;/> <flushOnExecute statement=&quot;delete&quot;/> </cacheModel> www.opensymphony.com/oscache/ www.opensymphony.com/oscache/documentation
Caching read-only, long-term data <cacheModel id=&quot; categoryCache &quot; type=&quot; LRU &quot;> <flushInterval hours=&quot; 24 &quot;/> <flushOnExecute statement=&quot; insert &quot;/> <flushOnExecute statement=&quot; update &quot;/> <flushOnExecute statement=&quot; delete &quot;/> <property name=&quot; size &quot; value=&quot; 50 &quot;/> </cacheModel> <select id=&quot; getChildCategories &quot; parameterClass=&quot; Category &quot; resultClass=&quot; Category &quot; cacheModel=&quot; categoryCache &quot;> SELECT * FROM category <dynamic prepend=&quot; WHERE  &quot;> <isNull property=&quot; categoryId &quot;> parentCategoryId IS NULL </isNull> <isNotNull property=&quot; categoryId &quot;> parentCategoryId=#categoryId:INTEGER:0# </isNotNull> </dynamic> ORDER BY sequence, title </select>
Caching read-write data <cacheModel id=&quot; productCache &quot; type=&quot; MEMORY &quot; readOnly=&quot; true &quot; serialize=&quot; false &quot;> <flushOnExecute statement=&quot; Product.add &quot; /> <flushOnExecute statement=&quot; Product.edit &quot; /> <flushOnExecute statement=&quot; Product.remove &quot; /> <property name=&quot; reference-type &quot; value=&quot; WEAK &quot; /> </cacheModel> <select id=&quot; getProductById &quot; resultClass=&quot; Product &quot; parameterClass=&quot; Product &quot; cacheModel=&quot; productCache &quot;> SELECT * FROM Product WHERE productId=#productId# </select>
Caching aging static data < cacheModel   id = &quot;hotProductCache&quot;   type = &quot;FIFO&quot; > < flushOnExecute   statement = &quot;Product.update&quot; /> < flushOnExecute   statement = &quot;Product.delete&quot; /> < property   name = &quot;size&quot;   value = &quot;12&quot; /> </ cacheModel > < select  id = &quot;getPopularProductsByPurchaseDate“  parameterClass = &quot;Product“  resultClass = &quot;Product&quot;   cacheModel = &quot;hotProductsCache&quot; > SELECT count(productId) countNum, productId FROM productPurchase WHERE purchaseDate BETWEEN #startDate# AND #endDate# GROUP BY productId ORDER BY countNum DESC LIMIT 5 </ select >

More Related Content

ODP
JSF 2 and Ajax
PDF
Palestra PythonBrasil[8]
PDF
Aplicacion turbogenerador java
PDF
Peek inside the fantastical Ukrainian Village home and studio of artists Jare...
PDF
JavaScript de qualidade: hoje, amanhã e sempre!
PDF
Proyecto Final Android-SQLite
PDF
Chief Keef's hologram can't catch a break, and it's a win for Keef
ODP
JavascriptMVC
JSF 2 and Ajax
Palestra PythonBrasil[8]
Aplicacion turbogenerador java
Peek inside the fantastical Ukrainian Village home and studio of artists Jare...
JavaScript de qualidade: hoje, amanhã e sempre!
Proyecto Final Android-SQLite
Chief Keef's hologram can't catch a break, and it's a win for Keef
JavascriptMVC

What's hot (7)

PPT
Spring Capitulo 04
PPTX
Jquery ui, ajax
PDF
PDF
2015 Key Ingredient Cook-Off
PDF
1- Sourcecode Array
PDF
Check out our photos of the Pixies' Metro show
PDF
Back To The Front - Javascript Test Driven Development is between us (workshop)
Spring Capitulo 04
Jquery ui, ajax
2015 Key Ingredient Cook-Off
1- Sourcecode Array
Check out our photos of the Pixies' Metro show
Back To The Front - Javascript Test Driven Development is between us (workshop)
Ad

Viewers also liked (16)

PDF
Introdução ao desenvolvimento Android - Notas Soltas
PDF
(번역)How to apply the international classification of functioning, disability ...
PDF
GWT training session 2
PDF
물리치료학회지 18권1호-04(논문투고)
PDF
Presentation de gwt maven
PDF
Secrets of the GWT
PDF
Transcranial direct current stimulation in stroke recovery
PPT
Bucharest GTUG - Roo and GWT - 01 June 2010
PDF
Inside Italia Maggio 2007 Raffaele Balducci: "L'humour vende"
ODT
Sin título 1
PPTX
PPTX
Manual de excel-FUNCIONES APRENDIDAS
PPT
Bloggen Met Vertrouwen
PDF
Grand Canyoneering with Aron Ralston
PDF
Batman o longo dia das bruxas 07
PPTX
bbbbbb
Introdução ao desenvolvimento Android - Notas Soltas
(번역)How to apply the international classification of functioning, disability ...
GWT training session 2
물리치료학회지 18권1호-04(논문투고)
Presentation de gwt maven
Secrets of the GWT
Transcranial direct current stimulation in stroke recovery
Bucharest GTUG - Roo and GWT - 01 June 2010
Inside Italia Maggio 2007 Raffaele Balducci: "L'humour vende"
Sin título 1
Manual de excel-FUNCIONES APRENDIDAS
Bloggen Met Vertrouwen
Grand Canyoneering with Aron Ralston
Batman o longo dia das bruxas 07
bbbbbb
Ad

More from Marcelo Honores (20)

PDF
Examen de certificacion de ADWORDS: C07-2 Presupuestos y ofertas II
PDF
Examen de certificacion de ADWORDS: C07-1 Presupuestos y Ofertas I
PDF
Examen de certificacion de ADWORDS: C08-2 medición y optimización
PDF
Examen de certificacion de ADWORDS: C08-1 Medición y optimización
PDF
Examen de certificacion de ADWORDS: C09:Rendimiento, rentabilidad y crecimiento
PDF
Examen de certificacion de ADWORDS: C10: Cómo gestionar varias cuentas
PPT
Health Synchronization
PPT
La economía de la abundancia
PPT
Billion Busienss Model Course
PPT
Beating the stress, depression, insomnia, and other mental problems
PPT
The power of sharing in business
PPT
The Billion Business Model
PPT
Data Acquisition Overview
PPT
Data acquisition & transformations in BI
PPT
Direct Access for Master Data
PPT
Delta Management excercise
PPT
Delta Management overview
PPT
Reporting: Conditions
PPT
Reporting:Variables
PPT
Reporting:Exceptions
Examen de certificacion de ADWORDS: C07-2 Presupuestos y ofertas II
Examen de certificacion de ADWORDS: C07-1 Presupuestos y Ofertas I
Examen de certificacion de ADWORDS: C08-2 medición y optimización
Examen de certificacion de ADWORDS: C08-1 Medición y optimización
Examen de certificacion de ADWORDS: C09:Rendimiento, rentabilidad y crecimiento
Examen de certificacion de ADWORDS: C10: Cómo gestionar varias cuentas
Health Synchronization
La economía de la abundancia
Billion Busienss Model Course
Beating the stress, depression, insomnia, and other mental problems
The power of sharing in business
The Billion Business Model
Data Acquisition Overview
Data acquisition & transformations in BI
Direct Access for Master Data
Delta Management excercise
Delta Management overview
Reporting: Conditions
Reporting:Variables
Reporting:Exceptions

iBatis course (beta)

  • 1. Curso de iBatis For smarties
  • 2. Instalando iBatis http://ibatis.apache.org/javadownloads.cgi Archivos: ibatis-2.3.4.726.zip Unziped ibatis-2.3.4.726.jar
  • 4. Configurando iBatis Crear el SqlMapConfig.xml Crear el db.properties Crear la clase java Crear el mapping para esa clase
  • 5. El SqlMapConfig.xml <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> <! DOCTYPE sqlMapConfig PUBLIC &quot;-//ibatis.apache.org//DTD SQL Map Config 2.0//EN&quot; &quot;http://ibatis.apache.org/dtd/sql-map-config-2.dtd&quot; > < sqlMapConfig > < properties resource = &quot;db.properties&quot; /> < settings useStatementNamespaces = &quot;false&quot; cacheModelsEnabled = &quot;true&quot; enhancementEnabled = &quot;true&quot; lazyLoadingEnabled = &quot;true&quot; maxRequests = &quot;32&quot; maxSessions = &quot;10&quot; maxTransactions = &quot;5&quot; /> < transactionManager type = &quot;JDBC&quot; > < dataSource type = &quot;SIMPLE&quot; > < property name = &quot;JDBC.Driver&quot; value = &quot;${driver}&quot; /> < property name = &quot;JDBC.ConnectionURL&quot; value = &quot;${url}&quot; /> < property name = &quot;JDBC.Username&quot; value = &quot;${user}&quot; /> < property name = &quot;JDBC.Password&quot; value = &quot;${pword}&quot; /> </ dataSource > </ transactionManager > < sqlMap resource = &quot;test/Encuesta.xml&quot; /> </ sqlMapConfig >
  • 6. El db.properties driver= com . mysql . jdbc .Driver url=jdbc:mysql:// localhost :3306/ encuesta user=root pword= mysql
  • 7. La clase Encuesta.java package 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; } }
  • 8. El mapa de la clase Encuesta.java <? xml version = &quot;1.0&quot; encoding = &quot;UTF-8&quot; ?> <! DOCTYPE sqlMap PUBLIC &quot;-//ibatis.apache.org//DTD SQL Map 2.0//EN&quot; &quot;http://ibatis.apache.org/dtd/sql-map-2.dtd&quot; > < sqlMap namespace = &quot;Encuesta&quot; > <!-- Use type aliases to avoid typing the full classname every time. --> < typeAlias alias = &quot;Encuesta&quot; type = &quot;enitity.Encuesta&quot; /> < resultMap id = &quot; EncuestaResult &quot; class = &quot;Encuesta&quot; > < result property = &quot; codigoEncuesta &quot; column = &quot; codigo_encuesta &quot; /> < result property = &quot; descripcionEncuesta &quot; column = &quot; descripcion_encuesta &quot; /> </ resultMap > <!-- Select with no parameters using the result map for Encuesta class. --> < select id = &quot; selectAllEncuestas &quot; resultMap = &quot;EncuestaResult&quot; > select * from encuesta </ select > < select id = &quot; selectEncuestaById &quot; parameterClass = &quot;int“ resultClass = &quot;Encuesta&quot; > select codigo_encuesta as codigoEncuesta, descripcion_encuesta as descripcionEncuesta from encuesta where codigo_encuesta = #codigoEncuesta# </ select >
  • 9. El mapa de la clase Encuesta.java <!-- Insert example, using the Encuesta parameter class --> < insert id = &quot; insertEncuesta &quot; parameterClass = &quot;Encuesta&quot; > insert into encuesta ( descripcion_encuesta values ( #descripcionEncuesta# ) </ insert > <!-- Update example, using the Encuesta parameter class --> < update id = &quot; updateEncuesta &quot; parameterClass = &quot;Encuesta&quot; > update encuesta set descripcion_encuesta = #descripcionEncuesta# where codigo_encuesta = #codigoEncuesta# </ update > <!-- Delete example, using an integer as the parameter class --> < delete id = &quot; deleteEncuestaById &quot; parameterClass = &quot;int&quot; > delete from encuesta where codigo_encuesta = #codigoEncuesta# </ delete > </ sqlMap >
  • 10. Test del bean Encuesta try { Reader reader = Resources. getResourceAsReader ( &quot;test/SqlMapConfig.xml&quot; ); sqlMapper = SqlMapClientBuilder. buildSqlMapClient (reader); reader.close(); } catch (IOException e) { // Fail fast. throw new RuntimeException( &quot;Something bad happened while building the SqlMapClient instance.&quot; + e, e); } . . . public static List selectAllAccounts () throws SQLException { return sqlMapper .queryForList ( &quot;selectAllEncuestas&quot; , new ArrayList ()); } public static Encuesta selectEncuestaById ( int id) throws SQLException { return (Encuesta) sqlMapper .queryForObject ( &quot;selectEncuestaById&quot; , id); } public static void insertEncuesta (Encuesta Encuesta) throws SQLException { sqlMapper .insert ( &quot;insertEncuesta&quot; , Encuesta); } public static void updateEncuesta (Encuesta Encuesta) throws SQLException { sqlMapper .update ( &quot;updateEncuesta&quot; , Encuesta); } public static void deleteEncuesta ( int id) throws SQLException { sqlMapper .delete ( &quot;deleteEncuesta&quot; , id); }
  • 11. Sentencias de mapas en iBatis
  • 12. Sentencias de mapas en iBatis
  • 13. El elemento <sql> < sql id = &quot;select-order&quot; > select * from order </ sql > < sql id = &quot;select-count&quot; > select count(*) as value from order </ sql > < sql id = &quot;where-shipped-after-value&quot; > <![CDATA[ where shipDate > #value:DATE# ]]> </ sql > < select id = &quot;getOrderShippedAfter&quot; resultClass = &quot;map&quot; > < include refid = &quot; select-order &quot; /> < include refid = &quot; where-shipped-after-value &quot; /> </ select > < select id = &quot;getOrderCountShippedAfter&quot; resultClass = &quot;int&quot; > < include refid = &quot; select-count &quot; /> < include refid = &quot; where-shipped-after-value &quot; /> </ select >
  • 14. How do I use LIKE in my WHERE clauses?” < select id = &quot;getByLikeCity&quot; resultClass = &quot;Account&quot; > select accountId, username , password, firstName, lastName, address1, address2, city, state, postalCode, country from Account where city like '%$value$%' </ select >
  • 15. Dynamic result mapping example < select id = &quot;getAccountRemapExample&quot; remapResults = &quot;true&quot; resultClass = &quot;java.util.HashMap&quot; > select accountId, username , < dynamic > < isEqual property = &quot;includePassword&quot; compareValue = &quot;true&quot; > password, </ isEqual > </ dynamic > firstName, lastName from Account < dynamic prepend = &quot; where &quot; > < isNotEmpty property = &quot;city&quot; > city like #city# </ isNotEmpty > < isNotNull property = &quot;accountId&quot; prepend = &quot; and &quot; > AccountId = #accountId# </ isNotNull > </ dynamic > </ select >
  • 16. Mapping parameters mode typeHandler nullValue jdbcType javaType property Attribute <select id=&quot;getOrderShippedAfter&quot; resultClass=&quot;java.util.HashMap&quot;> select * from order where shipDate > #value:DATE# </select>
  • 17. Ejemplo < select id = &quot;getOrderShippedAfter&quot; resultClass = &quot;hashmap&quot; > select * from &quot;order&quot; where shipDate > #value,jdbcType=DATE# </ select >
  • 18. iBATIS does not allow you to get a primitive result directly, Integer count = (Integer)sqlMap.queryForObject( &quot;Account.getOrderCountByAccount&quot;, new Integer(1)); <select id=&quot;getOrderCountByAccount&quot; resultClass=&quot; java.lang.Integer &quot; > select count(*) as value from order where accountId = #value# </select>
  • 19. public class PrimitiveResult { private int orderCount; public int getOrderCount() { return orderCount; } public void setOrderCount(int orderCount) { this.orderCount = orderCount; } } <resultMap id=&quot;primitiveResultMapExample“ class=&quot;PrimitiveResult&quot;> <result property=&quot;orderCount“ column=&quot;orderCount&quot; /> </resultMap> <select id=&quot;getPrimitiveById“ resultMap=&quot;primitiveResultMapExample&quot;> select count(*) as orderCount from order where accountId = #accountId# </select>
  • 20. JavaBean and Map results
  • 21. 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;
  • 24. Inserting data Using inline parameter mapping < insert id = &quot;insertWithInlineInfo&quot; > 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 >
  • 25. Inserting data Using inline parameter mapping Account account = new Account(); account.setAccountId(new Integer(9999)); account.setUsername(&quot; inlineins &quot;); account.setPassword(&quot; poohbear &quot;); account.setFirstName(&quot; Inline &quot;); account.setLastName(&quot; Example &quot;); sqlMapClient.insert(&quot; Account.insertWithInlineInfo &quot;, account);
  • 26. Inserting data Using an external parameter map < parameterMap id = &quot;fullParameterMapExample&quot; class = &quot;Account&quot; > < parameter property = &quot;accountId&quot; jdbcType = &quot;NUMBER&quot; /> < parameter property = &quot;username&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;password&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;memberSince&quot; jdbcType = &quot;TIMESTAMP&quot; /> < parameter property = &quot;firstName&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;lastName&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;address1&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;address2&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;city&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;state&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;postalCode&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;country&quot; jdbcType = &quot;VARCHAR&quot; /> < parameter property = &quot;version&quot; jdbcType = &quot;NUMBER&quot; /> </ parameterMap >
  • 27. Inserting data Using an external parameter map < insert id = &quot;insertWithExternalInfo&quot; parameterMap = &quot;fullParameterMapExample&quot; > insert into account ( accountId, username , password, memberSince firstName, lastName, address1, address2, city, state, postalCode, country, version ) values ( ?,?,?,?,?,?,?,?,?,?,?,?,? ) </ insert >
  • 28. Autogenerated keys Object insert( String id, Object parameterObject ) throws SQLException; <insert id=&quot;insert&quot;> <selectKey keyProperty=&quot;accountId“ resultClass=&quot;int&quot;> SELECT nextVal('account_accountid_seq') </selectKey> INSERT INTO Account ( accountId, username, password ) VALUES( #accountId#, #username#, #password# ) </insert> Integer returnValue = (Integer) sqlMap.insert(&quot;Account.insert&quot;, account);
  • 29. Autogenerated keys In SQL Server: <insert id=&quot;insert&quot;> INSERT INTO Account ( username, password ) VALUES( #username#, #password#) <selectKey keyProperty=&quot;accountId&quot; resultClass=&quot;int&quot;> SELECT SCOPE_IDENTITY() </selectKey> </insert> In MySQL: <insert id=&quot;insert&quot;> INSERT INTO Account ( username, password ) VALUES( #username#, #password#) <selectKey keyProperty=&quot;accountId&quot; resultClass=&quot;int&quot;> SELECT LAST_INSERT_ID( ) </selectKey> </insert>
  • 30. Updating or deleting child records public void saveOrder(SqlMapClient sqlMapClient, Order order) throws SQLException { if ( null == order.getOrderId()) { sqlMapClient.insert( &quot;Order.insert&quot; , order); } else { sqlMapClient.update( &quot;Order.update&quot; , order); } sqlMapClient.delete( &quot;Order.deleteDetails&quot; , order); for ( int i = 0; i < order.getOrderItems().size(); i++) { OrderItem oi = (OrderItem) order.getOrderItems().get(i); oi.setOrderId(order.getOrderId()); sqlMapClient.insert( &quot;OrderItem.insert&quot; , oi); } }
  • 31. Running batch updates public void saveOrder( SqlMapClient sqlMapClient, Order order) throws SQLException { sqlMapClient.startTransaction(); try { if ( null == order.getOrderId()) { sqlMapClient.insert( &quot;Order.insert&quot; , order); } else { sqlMapClient.update( &quot;Order.update&quot; , order); } sqlMapClient.startBatch(); sqlMapClient.delete( &quot;Order.deleteDetails&quot; , order); for ( int i = 0; i < order.getOrderItems().size(); i++) { OrderItem oi = ( OrderItem ) order.getOrderItems().get(i); oi.setOrderId(order.getOrderId()); sqlMapClient.insert( &quot;OrderItem.insert&quot; , oi); } sqlMapClient.executeBatch(); sqlMapClient.commitTransaction(); } finally { sqlMapClient.endTransaction(); } }
  • 32. Working with stored procedures CREATE OR REPLACE FUNCTION max_in_example (a float4, b float4) RETURNS float4 AS $BODY$ BEGIN if (a > b) then return a; else return b; end if; END; $BODY$ LANGUAGE 'plpgsql' VOLATILE;
  • 33. Working with stored procedures // En el Mapping ML <parameterMap id=&quot;pm_in_example&quot; class=&quot;java.util.Map&quot;> <parameter property=&quot;a&quot; /> <parameter property=&quot;b&quot; /> </parameterMap> <procedure id=&quot;in_example&quot; parameterMap=&quot;pm_in_example“ resultClass=&quot;int&quot; > { call max_in_example(?, ?) } </procedure> // EN Java Map m = new HashMap(2); m.put(&quot;a&quot;, new Integer(7)); m.put(&quot;b&quot;, new Integer(5)); Integer val = (Integer)sqlMap.queryForObject(&quot;Account.in_example&quot;, m);
  • 34. 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;
  • 35. Working with stored procedures <parameterMap id=&quot;maxOutProcedureMap&quot; class=&quot;java.util.Map&quot;> <parameter property=&quot;a&quot; mode=&quot;IN&quot; /> <parameter property=&quot;b&quot; mode=&quot;IN&quot; /> <parameter property=&quot;c&quot; mode=&quot;OUT&quot; /> </parameterMap> <procedure id=&quot;maxOutProcedure&quot; parameterMap=&quot;maxOutProcedureMap&quot;> { call maximum (?, ?, ?) } </procedure> // Call maximum function Map m = new HashMap(2); m.put(&quot;a&quot;, new Integer(7)); m.put(&quot;b&quot;, new Integer(5)); sqlMap.queryForObject(&quot;Account.maxOutProcedure&quot;, m); // m.get(&quot;c&quot;) should be 7 now.
  • 36. XML parameters < select id = &quot;getByXmlId&quot; resultClass = &quot;Account&quot; parameterClass = &quot;xml&quot; > select accountId, username , password, firstName, lastName, address1, address2, city, state, postalCode, country from Account where accountId = #accountId# </ select > String parameter = &quot;<parameter><accountId>3</accountId></parameter>&quot; ; Account account = ( Account ) sqlMapClient .queryForObject( &quot;Account.getByXmlId&quot; , parameter) ;
  • 37. XML parameters < select id = &quot;getByDomId&quot; resultClass = &quot;Account&quot; parameterClass = &quot;dom&quot; > select accountId, username , password, firstName, lastName, address1, address2, city, state, postalCode, country from Account where accountId = #accountId# </ select > Document parameterDocument = DocumentBuilderFactory .newInstance() .newDocumentBuilder().newDocument(); Element paramElement = parameterDocument .createElement( &quot;parameterDocument&quot; ); Element accountIdElement = parameterDocument .createElement( &quot;accountId&quot; ); accountIdElement . setTextContent( &quot;3&quot; ); paramElement . appendChild( accountIdElement ); parameterDocument . appendChild( paramElement ); Account account = ( Account ) sqlMapClient .queryForObject( &quot;Account.getByXmlId&quot; , parameterDocument );
  • 38. XML results <select id=&quot; getByIdValueXml &quot; resultClass=&quot; xml &quot; xmlResultName=&quot; account &quot;> select accountId, username, password from Account where accountId = #value# </select> String xmlData = (String) sqlMap.queryForObject(&quot; Account.getByIdValueXml &quot;, new Integer(1));
  • 39. XML results XML <select id=&quot; getByIdValueXml &quot; resultClass=&quot; xml &quot; xmlResultName=&quot; account &quot;> select accountId, username, password from Account where accountId = #value# </select> Java String xmlData = (String) sqlMap.queryForObject(&quot; Account.getByIdValueXml &quot;, new Integer(1)); Return <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <account> <accountid>1</accountid> <username>lmeadors</username> <password>blah</password> </account>
  • 40. XML parameters <select id=&quot; getAllXml &quot; resultClass=&quot; xml &quot; xmlResultName=&quot; account &quot;> select accountId, username, password, firstName, lastName, address1, address2, city, state, postalCode, country from Account </select> List xmlList = sqlMap.queryForList(&quot; Account.getAllXml &quot;, null);
  • 41. Automatic transactions public void runStatementsUsingAutomaticTransactions() { SqlMapClient sqlMapClient = SqlMapClientConfig.getSqlMapClient(); Person p = (Person) sqlMapClient.queryForObject(&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot; Smith &quot;); sqlMapClient.update(&quot; updatePerson &quot;, p); }
  • 42. Local transactions <transactionManager type=&quot;JDBC &quot;> <dataSource type=&quot;SIMPLE&quot;> <property …/> <property …/> <property …/> </dataSource> </transactionManager> public void runStatementsUsingLocalTransactions() { SqlMapClient sqlMapClient = SqlMapClientConfig.getSqlMapClient(); try { sqlMapClient.startTransaction(); Person p = (Person) sqlMapClient.queryForObject (&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot; Smith &quot;); sqlMapClient.update(&quot;updatePerson&quot;, p); Department d = (Department) sqlMapClient.queryForObject (&quot; getDept &quot;, new Integer(3)); p.setDepartment(d); sqlMapClient.update(&quot; updatePersonDept &quot;, p); sqlMapClient.commitTransaction(); } finally { sqlMapClient.endTransaction(); } }
  • 43. Global transactions <!– Active participation  <transactionManager type=&quot; JTA &quot;> <property name=&quot; UserTransaction &quot; value=&quot; java:/ctx/con/someUserTransaction &quot;/> <dataSource type=&quot; JNDI &quot;> <property name=&quot; DataSource &quot; value=&quot; java:comp/env/jdbc/someDataSource &quot;/> </dataSource> </transactionManager> <!– Pasive participation  <transactionManager type=&quot; EXTERNAL &quot;> <dataSource type=&quot; JNDI &quot;> <property name=&quot; DataSource &quot; value=&quot; java:comp/env/jdbc/someDataSource &quot;/> </dataSource> </transactionManager>
  • 44. Starting, committing, and ending the transaction public void runStatementsUsingGlobalTransactions() { SqlMapClient sqlMapClient = SqlMapClientConfig.getSqlMapClient(); try { sqlMapClient.startTransaction(); Person p = (Person)sqlMapClient.queryForObject (&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot;Smith&quot;); sqlMapClient.update(&quot;updatePerson&quot;, p); Department d = (Department)sqlMapClient.queryForObject (&quot; getDept &quot;, new Integer(3)); p.setDepartment(d); sqlMapClient.update(&quot; updatePersonDept &quot;, p); sqlMapClient.commitTransaction(); } finally { sqlMapClient.endTransaction(); } }
  • 45. 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 (&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot; Smith &quot;); sqlMapClient.update(&quot; updatePerson &quot;, p); Department d = (Department)sqlMapClient.queryForObject (&quot; getDept &quot;, new Integer(3)); p.setDepartment(d); sqlMapClient.update(&quot; updatePersonDept &quot;, p); conn.commit(); } finally { sqlMapClient.setUserConnection(null); if (conn != null) conn.close(); } }
  • 46. 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(&quot; getPerson &quot;, new Integer(9)); p.setLastName(&quot; Smith &quot;); session .update(&quot; updatePerson &quot;, p); Department d = (Department) session .queryForObject(&quot; getDept &quot;, new Integer(3)); p.setDepartment(d); session .update(&quot; updatePersonDept &quot;, p); conn.commit(); } finally { if (session != null) session.close(); if (conn != null) conn.close(); } }
  • 47. The ideal plae for transactions is the business layer
  • 48. Example of Dynamic WHERE clause … <select id=&quot; getChildCategories &quot; parameterClass=&quot;Category&quot; resultClass=&quot; Category &quot;> SELECT * FROM category <dynamic prepend=&quot; WHERE &quot;> <isNull property=&quot; parentCategoryId &quot;> parentCategoryId IS NULL </isNull> <isNotNull property=&quot; parentCategoryId &quot;> parentCategoryId=# parentCategoryId # </isNotNull> </dynamic> </select> …
  • 49. Mock removeFirstPrepend example … <dynamic prepend=&quot;WHERE &quot;> … <isNotEmpty property=&quot;y&quot;> y=#y# </isNotEmpty> <isNotNull property=&quot;x&quot; removeFirstPrepend=&quot;true&quot; prepend=&quot;AND&quot; open=&quot;(&quot; close=&quot;)&quot;> <isNotEmpty property=&quot;x.a&quot; prepend=&quot;OR&quot;> a=#x.a# </isNotEmpty> <isNotEmpty property=&quot;x.b&quot; prepend=&quot;OR&quot;> a=#x.b# </isNotEmpty> <isNotEmpty property=&quot;x.c&quot; prepend=&quot;OR&quot;> a=#x.c# </isNotEmpty> </isNotNull> … </dynamic> …
  • 51.  
  • 53. Binary tag example … <select id=&quot;getShippingType&quot; parameterClass=&quot;Cart&quot; resultClass=&quot;Shipping&quot;> SELECT * FROM Shipping <dynamic prepend=&quot; WHERE &quot;> <isGreaterEqual property=&quot; weight &quot; compareValue=&quot;100&quot;> shippingType= 'FREIGHT ' </isEqual> <isLessThan property=&quot; weight &quot; compareValue=&quot;100&quot;> shippingType= 'STANDARD ' </isLessThan> </dynamic> </select> …
  • 56. Unary tag example … <select id=&quot; getProducts &quot; parameterClass=&quot; Product &quot; resultClass=&quot; Product &quot;> SELECT * FROM Products <dynamic prepend=&quot; WHERE &quot;> <isNotEmpty property=&quot; productType &quot;> productType=#productType# </isNotEmpty> </dynamic> </select> …
  • 58. Parameter tag example … <select id=&quot;getProducts&quot; resultClass=&quot;Product&quot;> SELECT * FROM Products <isParameterPresent prepend=&quot;WHERE &quot;> <isNotEmpty property=&quot;productType&quot;> productType=#productType# </isNotEmpty> </ isParameterPresent > </select> …
  • 60. <iterate> tag example … <select id=&quot; getProducts &quot; parameterClass=&quot; Product &quot; resultClass=&quot; Product &quot;> SELECT * FROM Products <dynamic prepend=&quot; WHERE productType IN &quot;> <iterate property=&quot; productTypes “ open =&quot;(&quot; close=&quot; ) &quot; conjunction=&quot; ,&quot; > productType=#productType# </iterate> </dynamic> </select> …
  • 61. A simple iBATIS caching example <cacheModel id=&quot; categoryCache &quot; type=&quot; MEMORY &quot;> <flushOnExecute statement=&quot; insert &quot;/> <flushOnExecute statement=&quot; update &quot;/> <flushOnExecute statement=&quot; delete &quot;/> <property name=&quot; reference-type &quot; value=&quot; WEAK &quot;/> </cacheModel> <select id=&quot; getCategory &quot; parameterClass=&quot; Category &quot; resultClass=&quot; Category &quot; cacheModel=&quot; categoryCache &quot;> SELECT * FROM Category WHERE categoryId=#categoryId# </select>
  • 64. The readOnly attribute The <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.
  • 65. 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.
  • 66. Summary of readOnly and serialize attribute combinations
  • 68. flushOnExecute caching example <sqlMap namespace=&quot; Category &quot;> … <cacheModel id=&quot; categoryCache &quot; type=&quot; MEMORY &quot;> … <flushOnExecute statement=&quot; Category.insert &quot;/> … </cacheModel> … <select id=&quot; getCategory &quot; parameterClass=&quot; Category &quot; resultClass=&quot; Category &quot; cacheModel=&quot; categoryCache &quot;> SELECT * FROM Category WHERE parentCategoryId=#categoryId# </select> … <insert id=&quot; insert &quot; parameterClass=&quot; Category &quot; > INSERT INTO Category (title, description, sequence) VALUES (#title#,#description#,#sequence#) </insert> … </sqlMap>
  • 70. <flushInterval> caching example <sqlMap namespace=&quot; Category &quot;> … <cacheModel id=&quot; categoryCache &quot; type=&quot; MEMORY &quot;> … <flushInterval hours= &quot; 12 &quot; /> … </cacheModel> … <select id=&quot; getCategory &quot; parameterClass=&quot; Category &quot; resultClass=&quot; Category &quot; cacheModel=&quot; categoryCache &quot;> SELECT * FROM Category WHERE parentCategoryId=#categoryId# </select> … </sqlMap>
  • 71. Cache model types MEMORY LRU FIFO OSCACHE
  • 73. Sample MEMORY cacheModel <cacheModel id=&quot;categoryCache&quot; type=&quot;MEMORY&quot;> <flushInterval hours=&quot;24&quot;/> <flushOnExecute statement=&quot;insert&quot;/> <flushOnExecute statement=&quot;update&quot;/> <flushOnExecute statement=&quot;delete&quot;/> <property name=&quot;reference-type&quot; value=&quot;WEAK&quot;/> </cacheModel>
  • 74. LRU <cacheModel id=&quot;categoryCache&quot; type=&quot;LRU&quot;> <flushInterval hours=&quot;24&quot;/> <flushOnExecute statement=&quot;insert&quot;/> <flushOnExecute statement=&quot;update&quot;/> <flushOnExecute statement=&quot;delete&quot;/> <property name=&quot;size&quot; value=&quot;200&quot;/> </cacheModel>
  • 75. FIFO <cacheModel id=&quot;categoryCache&quot; type=&quot;FIFO&quot;> <flushInterval hours=&quot;24&quot;/> <flushOnExecute statement=&quot;insert&quot;/> <flushOnExecute statement=&quot;update&quot;/> <flushOnExecute statement=&quot;delete&quot;/> <property name=&quot;size&quot; value=&quot;1000&quot;/> </cacheModel>
  • 76. <cacheModel id=&quot;categoryCache&quot; type=&quot;OSCACHE&quot;> <flushInterval hours=&quot;24&quot;/> <flushOnExecute statement=&quot;insert&quot;/> <flushOnExecute statement=&quot;update&quot;/> <flushOnExecute statement=&quot;delete&quot;/> </cacheModel> www.opensymphony.com/oscache/ www.opensymphony.com/oscache/documentation
  • 77. Caching read-only, long-term data <cacheModel id=&quot; categoryCache &quot; type=&quot; LRU &quot;> <flushInterval hours=&quot; 24 &quot;/> <flushOnExecute statement=&quot; insert &quot;/> <flushOnExecute statement=&quot; update &quot;/> <flushOnExecute statement=&quot; delete &quot;/> <property name=&quot; size &quot; value=&quot; 50 &quot;/> </cacheModel> <select id=&quot; getChildCategories &quot; parameterClass=&quot; Category &quot; resultClass=&quot; Category &quot; cacheModel=&quot; categoryCache &quot;> SELECT * FROM category <dynamic prepend=&quot; WHERE &quot;> <isNull property=&quot; categoryId &quot;> parentCategoryId IS NULL </isNull> <isNotNull property=&quot; categoryId &quot;> parentCategoryId=#categoryId:INTEGER:0# </isNotNull> </dynamic> ORDER BY sequence, title </select>
  • 78. Caching read-write data <cacheModel id=&quot; productCache &quot; type=&quot; MEMORY &quot; readOnly=&quot; true &quot; serialize=&quot; false &quot;> <flushOnExecute statement=&quot; Product.add &quot; /> <flushOnExecute statement=&quot; Product.edit &quot; /> <flushOnExecute statement=&quot; Product.remove &quot; /> <property name=&quot; reference-type &quot; value=&quot; WEAK &quot; /> </cacheModel> <select id=&quot; getProductById &quot; resultClass=&quot; Product &quot; parameterClass=&quot; Product &quot; cacheModel=&quot; productCache &quot;> SELECT * FROM Product WHERE productId=#productId# </select>
  • 79. Caching aging static data < cacheModel id = &quot;hotProductCache&quot; type = &quot;FIFO&quot; > < flushOnExecute statement = &quot;Product.update&quot; /> < flushOnExecute statement = &quot;Product.delete&quot; /> < property name = &quot;size&quot; value = &quot;12&quot; /> </ cacheModel > < select id = &quot;getPopularProductsByPurchaseDate“ parameterClass = &quot;Product“ resultClass = &quot;Product&quot; cacheModel = &quot;hotProductsCache&quot; > SELECT count(productId) countNum, productId FROM productPurchase WHERE purchaseDate BETWEEN #startDate# AND #endDate# GROUP BY productId ORDER BY countNum DESC LIMIT 5 </ select >