SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
Omaha Java Users Group
   March 18, 2008
   Corey A. Spitzer
The Context



              • J2EE (with Spring)
              • OOP
              • SQL Relational Database
What is iBATIS?
Object Oriented



                  Object



  Logic / DAO
                           iBATIS           Database
     Code



                                    Query


                                             Relational
A More Detailed Look

              calls
   Code                       SqlMapClient
                                  insert()
                      loads      update()    calls
                                 delete()
                                  query()


     SQL Maps                                   javax.sql.DataSource
       Queries
     Result Maps

                                                      Magic
                                                      Magic




                                                     Database
The SQL Map Anatomy                               Code
                                                          calls SqlMapClient

                                                          loads                calls

                                                   SQL Maps                            DataSource



<sqlMap namespace="myNamespace">                                                         Magic
                                                                                          Magic

       <resultMap id="myClass" class="full.package.MyClass">
                                                                                       Database
                <result property="foo" column="col1"/>
                <result property="bar" column="col2"/>
                ...
       </resultMap>
       ...
       <!-- ===================================================== -->
       <sql id="myQuery" resultMap="myClass">
                SELECT col1, col2 FROM table1
       </sql>
       ...
</sqlMap>
The Code Anatomy                                 Code
                                                         calls SqlMapClient

                                                         loads                calls
import java.sql.SQLException;
                                                  SQL Maps                            DataSource
import com.ibatis.sqlmap.client.SqlMapClient;
...                                                                                     Magic
                                                                                         Magic

public class MyDAO
                                                                                      Database
{
       private SqlMapClient myDB;


       public void frobnicate(MyObject someObject) throws SQLException
       {
              List<MyClass> list = myDB.queryForList("myQuery");
              Foo myFoo = (Foo)myDB.queryForObject("getFooByID", 1337);
              myDB.update("myQuery3");
              myDB.insert("myQuery4", someObject);
              ...
       }
       ...
}
Any Questions so far?

              calls
   Code                       SqlMapClient
                                  insert()
                      loads      update()    calls
                                 delete()
                                  query()


     SQL Maps                                   javax.sql.DataSource
       Queries
     Result Maps

                                                      Magic
                                                      Magic




                                                     Database
Implicit Mapping

<sqlMap namespace="myNamespace">
       <resultMap id="myClass" class="full.package.Class">
                <result property="foo" column="col1"/>
                <result property="bar" column="col2"/>
                ...
       </resultMap>
       ...
       <!-- ===================================================== -->
       <sql id="myQuery" resultClass="full.package.Class">
                SELECT col1 as foo, col2 as bar FROM table1
       </sql>
       ...
</sqlMap>
Inheritance
    Object Oriented Code                      Relational Database

               Fruit                                     fruits
         id - int                             id - mediumint(7), PK
         dateBought - long                    date_bought - int(11)
                                              type - enum('a', 'o')



                                                       apples
    Apple                Orange               fruit_id - mediumint(7), FK
                                              worm_count - decimal(4,1)
wormCount - float   bioengineered - boolean

                                                      oranges
                                              fruit_id - mediumint(7), FK
                                              bioengineered - bool
Complex Members
  Object Oriented Code             Relational Database

             Cake                             cakes
    id - int                       id - mediumint(7), PK
    flavor - String                flavor - enum('chocolate', ...)
    toppings - List<CakeTopping>


                                   cakes_to_toppings
                                   cake_id - mediumint(7), FK
                                   topping_id - mediumint(7), FK
        CakeTopping
     id - int
     name - String                    cake_toppings
     containsHFCS - boolean
                                   id - mediumint(7), PK
                                   name - varchar(20)
                                   contains_hfcs - bool
Parameters & Dynamic Queries
Custom Type Handlers
public class YesNoBoolTypeHandler implements TypeHandlerCallback {
        public Object getResult(ResultGetter getter) throws SQLException {
                 if ("Y".equalsIgnoreCase(getter.getString())) {
                            return new Boolean (true);
                 } else if ("N".equalsIgnoreCase(getter.getString())) {
                            return new Boolean (false);
                 } else {
                            throw new SQLException();
                 }
        }
        public void setParameter(ParameterSetter setter, Object parameter)
        throws SQLException {
                 if (((Boolean)parameter).booleanValue()) setter.setString("Y");
                 else setter.setString("N");
        }
        public Object valueOf(String s) {
                 return new Boolean ("Y".equalsIgnoreCase(s));
        }
}
Custom Type Handlers

<resultMap id="myClass" class="my.package.MyClass">
   ...
   <result property="foo" column="bar"
   typeHandler="some.package.YesNoBoolTypeHandler"/>
   ...
</resultMap>




<insert id="myQuery" resultMap="myClass"
parameterClass="my.package.MyClass">
         INSERT INTO table1 SET bar =
         #foo,handler=some.package.YesNoBoolTypeHandler#
</insert>
Paging / Selecting a Range
selectKey

<insert id="addForumThread" parameterClass="java.util.HashMap">
   INSERT INTO forum_threads SET
   forum_id = #forumID#,
   title = #title#,
   created_time = #createdTime#,
   last_updated_time = #createdTime#,
   <selectKey resultClass="int">
       SELECT MAX(id) FROM forum_threads
   </selectKey>
</insert>
Caching Features
<cacheModel id="fooCache" type="{LRU|MEMORY|FIFO|OSCACHE}"
readOnly="{true|false}" serialize="{true|false}">
      <flushInterval hours="24"/>
      <flushOnExecute statement="insertFoo"/>
      <flushOnExecute statement="updateFoo"/>
      <flushOnExecute statement="deleteFoo"/>
      <property name="size" value="1000"/>
</cacheModel>


<select id="getFoo" cacheModel="fooCache">
         SELECT * FROM bar WHERE id = #value#
</select>


<insert id="insertFoo">
         INSERT INTO bar SET ...
</insert>
...
Transactions
public updateItemDescription(String itemId, String newDescription)
throws SQLException
{
       try
       {
               sqlMap.startTransaction();

                 Item item = (Item)
                        sqlMap.queryForObject("getItem", itemId);

                 item.setDescription (newDescription);

                 sqlMap.update("updateItem", item);

                 sqlMap.commitTransaction();
       }
       finally
       {

                 sqlMap.endTransaction();
       }
}
What About Hibernate?

            iBATIS                                    Hibernate
• Separation of code and SQL                • SQL alongside code

• Simpler configuration and setup*

• Total control over SQL queries            • Cross-DB query language (HQL)

• Shallow learning curve                    • ???

• Handles application complexities          • Works very well when data model
better**                                    closely resembles object model**



          **No Fluff Just Stuff's Mark Richards' two cents:
          http://www.nofluffjuststuff.com/media.jsp?mediaId=27


             *Source: http://www.devx.com/Java/Article/31481/0/page/1
Who is Using iBatis?

                       • CNet.com

                       • MySpace.com

                       • OfficeMax.com

                       • JPMorganChase.com

                       • 1up.com

                       • PowerSentry.com

                       (and more)


     Source: http://www.ociweb.com/mark/programming/iBATIS.html#WhoUses
Now What?


       http://ibatis.apache.org

Mais conteúdo relacionado

Mais procurados

JavaFX and Scala in the Cloud
JavaFX and Scala in the CloudJavaFX and Scala in the Cloud
JavaFX and Scala in the CloudStephen Chin
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLJohn David Duncan
 
GR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM OptimizationGR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM OptimizationGR8Conf
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Ralph Schindler
 
Wed 1630 greene_robert_color
Wed 1630 greene_robert_colorWed 1630 greene_robert_color
Wed 1630 greene_robert_colorDATAVERSITY
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Java FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's GuideJava FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's GuideStephen Chin
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database JonesJohn David Duncan
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Scott Leberknight
 
React responsively, render responsibly - react meetup
React responsively, render responsibly - react meetupReact responsively, render responsibly - react meetup
React responsively, render responsibly - react meetupYoav Niran
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2eugenio pombi
 
JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?gedoplan
 
FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.UA Mobile
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 

Mais procurados (19)

Java &amp; banco de dados
Java &amp; banco de dadosJava &amp; banco de dados
Java &amp; banco de dados
 
JavaFX and Scala in the Cloud
JavaFX and Scala in the CloudJavaFX and Scala in the Cloud
JavaFX and Scala in the Cloud
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
GR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM OptimizationGR8Conf 2011: GORM Optimization
GR8Conf 2011: GORM Optimization
 
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
 
Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2
 
Wed 1630 greene_robert_color
Wed 1630 greene_robert_colorWed 1630 greene_robert_color
Wed 1630 greene_robert_color
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Java FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's GuideJava FX 2.0 - A Developer's Guide
Java FX 2.0 - A Developer's Guide
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 
React responsively, render responsibly - react meetup
React responsively, render responsibly - react meetupReact responsively, render responsibly - react meetup
React responsively, render responsibly - react meetup
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?JUG Berlin Brandenburg: What's new in Java EE 7?
JUG Berlin Brandenburg: What's new in Java EE 7?
 
FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.FormsKit: reactive forms driven by state. UA Mobile 2017.
FormsKit: reactive forms driven by state. UA Mobile 2017.
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 

Destaque

Cấu hình Hibernate
Cấu hình HibernateCấu hình Hibernate
Cấu hình HibernateMinh Quang
 
Hướng dẫn lập trình java hibernate cho người mới bắt đầu
Hướng dẫn lập trình java hibernate cho người mới bắt đầuHướng dẫn lập trình java hibernate cho người mới bắt đầu
Hướng dẫn lập trình java hibernate cho người mới bắt đầuThành Phạm Đức
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationLuis Goldster
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkPhuoc Nguyen
 

Destaque (6)

Cấu hình Hibernate
Cấu hình HibernateCấu hình Hibernate
Cấu hình Hibernate
 
Hướng dẫn lập trình java hibernate cho người mới bắt đầu
Hướng dẫn lập trình java hibernate cho người mới bắt đầuHướng dẫn lập trình java hibernate cho người mới bắt đầu
Hướng dẫn lập trình java hibernate cho người mới bắt đầu
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 

Semelhante a iBATIS

NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
Using Spark to Load Oracle Data into Cassandra (Jim Hatcher, IHS Markit) | C*...
Using Spark to Load Oracle Data into Cassandra (Jim Hatcher, IHS Markit) | C*...Using Spark to Load Oracle Data into Cassandra (Jim Hatcher, IHS Markit) | C*...
Using Spark to Load Oracle Data into Cassandra (Jim Hatcher, IHS Markit) | C*...DataStax
 
Using Spark to Load Oracle Data into Cassandra
Using Spark to Load Oracle Data into CassandraUsing Spark to Load Oracle Data into Cassandra
Using Spark to Load Oracle Data into CassandraJim Hatcher
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)Craig Dickson
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinDmitry Pranchuk
 
Deeply Declarative Data Pipelines
Deeply Declarative Data PipelinesDeeply Declarative Data Pipelines
Deeply Declarative Data PipelinesHostedbyConfluent
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapperSF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapperChester Chen
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptCaridy Patino
 
Data Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data ManagementData Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data ManagementMongoDB
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 

Semelhante a iBATIS (20)

NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
Using Spark to Load Oracle Data into Cassandra (Jim Hatcher, IHS Markit) | C*...
Using Spark to Load Oracle Data into Cassandra (Jim Hatcher, IHS Markit) | C*...Using Spark to Load Oracle Data into Cassandra (Jim Hatcher, IHS Markit) | C*...
Using Spark to Load Oracle Data into Cassandra (Jim Hatcher, IHS Markit) | C*...
 
Using Spark to Load Oracle Data into Cassandra
Using Spark to Load Oracle Data into CassandraUsing Spark to Load Oracle Data into Cassandra
Using Spark to Load Oracle Data into Cassandra
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)JDBC Basics (In 20 Minutes Flat)
JDBC Basics (In 20 Minutes Flat)
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
Jdbc
JdbcJdbc
Jdbc
 
Requery overview
Requery overviewRequery overview
Requery overview
 
Paging Like A Pro
Paging Like A ProPaging Like A Pro
Paging Like A Pro
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on Kotlin
 
JavaScript JQUERY AJAX
JavaScript JQUERY AJAXJavaScript JQUERY AJAX
JavaScript JQUERY AJAX
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Deeply Declarative Data Pipelines
Deeply Declarative Data PipelinesDeeply Declarative Data Pipelines
Deeply Declarative Data Pipelines
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapperSF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
Data Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data ManagementData Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data Management
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 

Mais de techmonkey4u

Overview of Human and Computer Vision
Overview of Human and Computer VisionOverview of Human and Computer Vision
Overview of Human and Computer Visiontechmonkey4u
 
Robot Exploration with Combinatorial Auctions
Robot Exploration with Combinatorial AuctionsRobot Exploration with Combinatorial Auctions
Robot Exploration with Combinatorial Auctionstechmonkey4u
 
Brain Architecture
Brain ArchitectureBrain Architecture
Brain Architecturetechmonkey4u
 
Fundamental HTML and CSS
Fundamental HTML and CSSFundamental HTML and CSS
Fundamental HTML and CSStechmonkey4u
 
A Brief Overview of OpenCV
A Brief Overview of OpenCVA Brief Overview of OpenCV
A Brief Overview of OpenCVtechmonkey4u
 
A Discussion on Automatic Programming
A Discussion on Automatic ProgrammingA Discussion on Automatic Programming
A Discussion on Automatic Programmingtechmonkey4u
 

Mais de techmonkey4u (6)

Overview of Human and Computer Vision
Overview of Human and Computer VisionOverview of Human and Computer Vision
Overview of Human and Computer Vision
 
Robot Exploration with Combinatorial Auctions
Robot Exploration with Combinatorial AuctionsRobot Exploration with Combinatorial Auctions
Robot Exploration with Combinatorial Auctions
 
Brain Architecture
Brain ArchitectureBrain Architecture
Brain Architecture
 
Fundamental HTML and CSS
Fundamental HTML and CSSFundamental HTML and CSS
Fundamental HTML and CSS
 
A Brief Overview of OpenCV
A Brief Overview of OpenCVA Brief Overview of OpenCV
A Brief Overview of OpenCV
 
A Discussion on Automatic Programming
A Discussion on Automatic ProgrammingA Discussion on Automatic Programming
A Discussion on Automatic Programming
 

Último

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Último (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

iBATIS

  • 1. Omaha Java Users Group March 18, 2008 Corey A. Spitzer
  • 2. The Context • J2EE (with Spring) • OOP • SQL Relational Database
  • 3. What is iBATIS? Object Oriented Object Logic / DAO iBATIS Database Code Query Relational
  • 4. A More Detailed Look calls Code SqlMapClient insert() loads update() calls delete() query() SQL Maps javax.sql.DataSource Queries Result Maps Magic Magic Database
  • 5. The SQL Map Anatomy Code calls SqlMapClient loads calls SQL Maps DataSource <sqlMap namespace="myNamespace"> Magic Magic <resultMap id="myClass" class="full.package.MyClass"> Database <result property="foo" column="col1"/> <result property="bar" column="col2"/> ... </resultMap> ... <!-- ===================================================== --> <sql id="myQuery" resultMap="myClass"> SELECT col1, col2 FROM table1 </sql> ... </sqlMap>
  • 6. The Code Anatomy Code calls SqlMapClient loads calls import java.sql.SQLException; SQL Maps DataSource import com.ibatis.sqlmap.client.SqlMapClient; ... Magic Magic public class MyDAO Database { private SqlMapClient myDB; public void frobnicate(MyObject someObject) throws SQLException { List<MyClass> list = myDB.queryForList("myQuery"); Foo myFoo = (Foo)myDB.queryForObject("getFooByID", 1337); myDB.update("myQuery3"); myDB.insert("myQuery4", someObject); ... } ... }
  • 7. Any Questions so far? calls Code SqlMapClient insert() loads update() calls delete() query() SQL Maps javax.sql.DataSource Queries Result Maps Magic Magic Database
  • 8. Implicit Mapping <sqlMap namespace="myNamespace"> <resultMap id="myClass" class="full.package.Class"> <result property="foo" column="col1"/> <result property="bar" column="col2"/> ... </resultMap> ... <!-- ===================================================== --> <sql id="myQuery" resultClass="full.package.Class"> SELECT col1 as foo, col2 as bar FROM table1 </sql> ... </sqlMap>
  • 9. Inheritance Object Oriented Code Relational Database Fruit fruits id - int id - mediumint(7), PK dateBought - long date_bought - int(11) type - enum('a', 'o') apples Apple Orange fruit_id - mediumint(7), FK worm_count - decimal(4,1) wormCount - float bioengineered - boolean oranges fruit_id - mediumint(7), FK bioengineered - bool
  • 10. Complex Members Object Oriented Code Relational Database Cake cakes id - int id - mediumint(7), PK flavor - String flavor - enum('chocolate', ...) toppings - List<CakeTopping> cakes_to_toppings cake_id - mediumint(7), FK topping_id - mediumint(7), FK CakeTopping id - int name - String cake_toppings containsHFCS - boolean id - mediumint(7), PK name - varchar(20) contains_hfcs - bool
  • 12. Custom Type Handlers public class YesNoBoolTypeHandler implements TypeHandlerCallback { public Object getResult(ResultGetter getter) throws SQLException { if ("Y".equalsIgnoreCase(getter.getString())) { return new Boolean (true); } else if ("N".equalsIgnoreCase(getter.getString())) { return new Boolean (false); } else { throw new SQLException(); } } public void setParameter(ParameterSetter setter, Object parameter) throws SQLException { if (((Boolean)parameter).booleanValue()) setter.setString("Y"); else setter.setString("N"); } public Object valueOf(String s) { return new Boolean ("Y".equalsIgnoreCase(s)); } }
  • 13. Custom Type Handlers <resultMap id="myClass" class="my.package.MyClass"> ... <result property="foo" column="bar" typeHandler="some.package.YesNoBoolTypeHandler"/> ... </resultMap> <insert id="myQuery" resultMap="myClass" parameterClass="my.package.MyClass"> INSERT INTO table1 SET bar = #foo,handler=some.package.YesNoBoolTypeHandler# </insert>
  • 15. selectKey <insert id="addForumThread" parameterClass="java.util.HashMap"> INSERT INTO forum_threads SET forum_id = #forumID#, title = #title#, created_time = #createdTime#, last_updated_time = #createdTime#, <selectKey resultClass="int"> SELECT MAX(id) FROM forum_threads </selectKey> </insert>
  • 16. Caching Features <cacheModel id="fooCache" type="{LRU|MEMORY|FIFO|OSCACHE}" readOnly="{true|false}" serialize="{true|false}"> <flushInterval hours="24"/> <flushOnExecute statement="insertFoo"/> <flushOnExecute statement="updateFoo"/> <flushOnExecute statement="deleteFoo"/> <property name="size" value="1000"/> </cacheModel> <select id="getFoo" cacheModel="fooCache"> SELECT * FROM bar WHERE id = #value# </select> <insert id="insertFoo"> INSERT INTO bar SET ... </insert> ...
  • 17. Transactions public updateItemDescription(String itemId, String newDescription) throws SQLException { try { sqlMap.startTransaction(); Item item = (Item) sqlMap.queryForObject("getItem", itemId); item.setDescription (newDescription); sqlMap.update("updateItem", item); sqlMap.commitTransaction(); } finally { sqlMap.endTransaction(); } }
  • 18. What About Hibernate? iBATIS Hibernate • Separation of code and SQL • SQL alongside code • Simpler configuration and setup* • Total control over SQL queries • Cross-DB query language (HQL) • Shallow learning curve • ??? • Handles application complexities • Works very well when data model better** closely resembles object model** **No Fluff Just Stuff's Mark Richards' two cents: http://www.nofluffjuststuff.com/media.jsp?mediaId=27 *Source: http://www.devx.com/Java/Article/31481/0/page/1
  • 19. Who is Using iBatis? • CNet.com • MySpace.com • OfficeMax.com • JPMorganChase.com • 1up.com • PowerSentry.com (and more) Source: http://www.ociweb.com/mark/programming/iBATIS.html#WhoUses
  • 20. Now What? http://ibatis.apache.org