SlideShare una empresa de Scribd logo
1 de 54
Descargar para leer sin conexión
Apache iBatis

Getting Up to Speed
    Carsten Ziegeler
    cziegeler@apache.org

    Day Software
About Carsten Ziegeler
• Apache Software Foundation Member
  – Cocoon, Excalibur, Pluto, Felix, Incubator,
    Sling, Sanselan
  – PMC: Cocoon, Incubator, Portals, Felix,
    Excalibur (Chair)
• Senior Developer at Day Software
• Article/Book Author, Technical Reviewer
• JSR 286 spec group (Portlet API 2.0)
and jobs!
                                          infos, discussions
                                          Visit our booth for
              Apache iBatis
    Quick Intro
•
    Quick Start Guide
•
•   The Data Mapping
•   The Database Configuration
•   Summary



                                      3
A Common Problem
    Reading from / writing to a database in Java
•
    Mapping of result sets to objects
•
•   Mapping of objects to tables/columns
•   Object Relational Mapping (ORM)




                                            4
Why do I need iBatis?
• Several ORM solutions out there
  –   Hibernate, Apache OpenJPA, Apache OJB
  –   Very sophisticated, but quot;heavyquot; solutions
  –   Usable for literally everything
  –   Setting up, configuring, using takes time
• What about javax.sql/JDBC?
  – ….if you think that SQL and Java code mixes
    well
                                                  5
Why do I need iBatis?
• Apache iBatis fits in-between
  –   Small library
  –   Simple setup
  –   Easy to use
  –   Uses data maps




                                  6
Use the Right Tool!
• Not every tool is suited for every use case!
  – Analyze requirements
  – Decide for the tool
  – Constantly check decision
• Apache iBatis is not suited for all ORM
  problems


                                            7
Some Typical Scenarios for
             iBatis
• Reading dictionaries (like i18n translations)
• Performing complex and nested queries
  – Full SQL support
• Reading configuration
• Writing log statements
• Displaying query results


                                           8
The Project
• Popular tool
  – Abstracting JDBC
  – Working at the SQL level
• Started by Clinton Begin
  – Part of Apache since 2005
  – Top level project
• Current version 2.x (> 3 years old)
  – Next major version in design discussions
                                               9
The Project
• Two frameworks
  – iBatis Data Mapper
  – iBatis Data Access Objects
• Implementations for different languages
  – Java, .Net, Ruby/Rails
• Focus on the Java Data Mapper


                                        10
How Does it Work?
    SQL statements are defined in XML
•
    Statements can contain placeholders
•
•   Placeholders are replaced on execution
•   SQL query result is mapped to objects




                                             11
Some Advantages
• Retain the full power of SQL
    – Functions like avg, sum, count etc.
    – Mapping across tables
•   Single point of configuration
•   Short integration time
•   Very good documentation
•   Caching of query results

                                            12
Caveats
    No transparent persistence
•
    No change detection
•
•   Explicit mapping required
•   No implicit operations (like cascaded
    updates, deletes etc.)



                                            13
Installation
• Download and add to classpath
• Optional 3rd party jars for additional stuff
    – Refer to the documentation
File Name           Description                    Required

ibatis-common.jar   iBATIS Common Utilities        YES
ibatis-sqlmap.jar   iBATIS Data Mapper Framework   YES
ibatis-dao.jar      iBATIS Data Access Framework   NO



                                                              14
Data Mapper Concept




                      15
Apache iBatis
    Quick Intro
•
    Quick Start Guide
•
•   The Data Mapping
•   The Database Configuration
•   Summary



                                 16
Four Basic Steps
1.   Write Java beans (optional)
2.   Create mapping configuration
3.   Specify the SQL configuration
4.   Write the app code executing the
     statements



                                        17
1. Write Java Beans (optional)
• Use primitive types for properties
• Alternative: maps
                                         Person.java
public class Person {
   private long personId;
   private String name;
   private java.util.Date dateOfBirth;

  // getters and setters:
  ...




                                              18
2. Create Mapping Configuration
                                                   Person.xml
<sqlMap namespace=quot;Personquot;>

  <select id=quot;getPersonquot; resultClass=quot;samples.Personquot;
          parameterClass=quot;longquot;>
     SELECT id               as personId
     ,     p_name            as name
     ,     date_of_birth      as dateOfBirth
     FROM person_t pers
     WHERE pers.id = #value#
  </select>
</sqlMap>




                                                        19
3. Specify the SQL Configuration
                                            sql-map-config.xml
<sqlMapConfig>

  <transactionManager type=quot;JDBCquot;>
    <dataSource type=quot;SIMPLEquot;>
      <property ...
      ...
    </dataSource>
  </transactionManager>

  <sqlMap resource=quot;samples/maps/Person.xmlquot;/>

</sqlMapConfig>




                                                       20
4. Write the App Code
                                                     DAO.java
public Person getPerson(long id) {
   Person p = null;
   try {
      // Configure iBatis
      Reader reader = Resources.getResourceAsReader
                (quot;samples/sql-map-config.xmlquot;);
      SqlMapClient sqlMap =
             SqlMapClientBuilder.buildSqlMapClient(reader);

       // execute
       p = (Person)sqlMap.queryForObject(quot;getPersonquot;, id);
    } catch (Exception e) {
       // do something useful here
    }
    return p;
}



                                                        21
Apache iBatis
    Quick Intro
•
    Quick Start Guide
•
•   The Data Mapping
•   The Database Configuration
•   Summary



                                 22
The Data Mapping
• Define mapping between Java objects and
  SQL
• XML configuration file(s)
• iBatis offers many possibilities/features
  – The following is just an overview
  – Check out the docs
  – (Often maps are sufficient)
Mapping Elements
• Mapping Java beans to SQL statements
• More than one config file possible
 <sqlMap>

   <typeAlias/> *
   <parameterMap/> *

   <resultMap/> *

   <statement/> *
   <select | insert | update | delete | procedure/> *
 </sqlMap>



                                                        24
Data Mapper Concept
• Mapped statements
   – SQL
   – Parameter maps (input)
   – Result maps (output)

 <select id=quot;getAllUsersquot; resultMap=quot;Userquot;>
     SELECT id, username, password, active
     FROM user_t
 </select>




                                              25
Querying the Database
• Unique identifier
• Result and parameter class
• SQL statements (it's XML!)
<select id=quot;getOlderThanquot; resultClass=quot;Personquot; parameterClass=quot;datequot;>
  <![CDATA[
    SELECT id as personID
           , ...
    FROM person_t pers
    WHERE date_of_birth > #value#
  ]]>
</select>




                                                               26
Parameters: Primitive Types
• Primitive types can directly be used for
  input
    – e.g. String, Integer, Date, etc.
    – #value# references the actual value
<statement id=quot;getPersonquot; parameterClass=quot;java.lang.Integerquot;>
          SELECT * FROM product_t
  WHERE product_id = #value#
</statement>

sqlMapClient.queryForObject(quot;getPersonquot;, new Integer(1));



                                                        27
Parameters: Beans
• Mapping description: bean -> input
    –   Properties
    –   Optional type definition: Java and JDBC
    –   Optional null values
    –   Optional type handler for conversion
<parameterMap id=quot;parameterMapNamequot; [class=quot;someDomainClassquot;]>
   <parameter property=quot;propertyNamequot; [jdbcType=quot;VARCHARquot;]
       [javaType=quot;stringquot;] [nullValue=quot;-1quot;]
       [typeHandler=quot;someHandlerquot;]/>
   <parameter .../>
</parameterMap>

                                                        28
Parameters: Beans
• Properties are applied in order of definition
   <parameterMap id=quot;personMapquot;
                 class=quot;samples.Personquot;>
      <parameter property=quot;namequot;/>
      <parameter property=quot;dateOfBirthquot;/>
      <parameter property=quot;addressquot;/>
   </parameterMap>

   <insert id=quot;insertPersonquot; parameterMap=quot;personMapquot;>
      INSERT INTO person_t
      (name, date_of_birth, address)
      VALUES (?, ?, ?)
   </insert>




                                                         29
Parameters: Inline Beans
• Less verbose form of parameter maps
  – Inline property names

<insert id=quot;insertPersonquot; parameterMap=quot;samples.Personquot;>
   INSERT INTO person_t
   (name, date_of_birth, address)
   VALUES (#name#, #dateOfBirth#, #address#)
</insert>




                                                       30
Parameters: Inline Beans
• Support for types and null values
<insert id=quot;insertPersonquot; parameterMap=quot;samples.Personquot;>
   INSERT INTO person_t
   (name, date_of_birth, address)
   VALUES (#name#, #dateOfBirth#, #address:VARCHAR:NO_ADDR#)
</insert>




                                                       31
Parameters: Maps
• Alternative to custom beans: maps
   – java.util.HashMap etc.
   – #key# references the value stored for key
<statement id=quot;getAddressesquot; parameterClass=quot;java.util.Mapquot;>
          SELECT * FROM addresses_t
          WHERE person_id = #personID#
          AND category_information = #category#
</statement>

params.put(quot;personIDquot;, new Integer(1));
params.put(quot;categoryquot;, quot;Businessquot;);
sqlMapClient.queryForList(quot;getAddressesquot;, params);

                                                       32
Result Maps
• Mapping result sets to beans
  –   Properties/columns
  –   Optional type definition: Java and JDBC
  –   Optional null values
  –   Optional type handler for conversion
       <resultMap id=quot;resultMapNamequot; class=quot;someDomainClassquot;
                  [extends=quot;parent-resultMapquot;]>
         <result property=quot;propertyNamequot; column=quot;COLUMN_NAMEquot;
                    [javaType=quot;intquot;] [jdbcType=quot;NUMERICquot;]
                    [nullVlaue=quot;-1quot;]
       [typeHandler=quot;someHandlerquot;]/>
         <result .../>
       </resultMap>
                                                       33
Result Maps: Inline
• Direct mapping

<select id=quot;getPersonquot; parameterClass=quot;longquot;
                       resultClass=quot;samples.Personquot;>
  SELECT id AS personID
  , first_name AS firstName
  , email
  , ...
  FROM person_t pers
  WHERE pers.id = #value#        public class Person {
</select>                          private long personID;
                                    private String firstName;
                                    private String email;
                                    ...



                                                            34
Primitive Results
• Primitive types can directly be used
    – e.g. String, Integer, Date, etc.
    – Result map or inline
<resultMap id=quot;get-resultquot; resultClass=quot;java.lang.Integerquot;>
   <result property=quot;valuequot; column=quot;NUMBER_OF_CUSTOMERSquot;/>
</resultMap>

<statement id=quot;getPersonCountquot; resultClass=quot;intquot;
   SELECT count(*) AS value
   FROM person_t
</statement>


                                                        35
Map Results
• Alternative to custom beans: maps
   – java.util.HashMap etc.
  <resultMap id=quot;result-mapquot; resultClass=quot;java.util.HashMapquot;>
     <result property=quot;idquot; column=quot;IDquot;/>
     <result property=quot;titlequot; column=quot;TITLEquot;/>
     <result property=quot;speakerquot; column=quot;SPEAKER_NAMEquot;/>
  </resultMap>

  <select id=quot;getAllSessionsquot; resultMap=quot;result-mapquot;>
   SELECT id, title, speaker_name
   FROM sessions_t
  </select>                 sqlmap.queryForList(quot;getAllSessionsquot;)

                                {id=1, title=iBatis, speaker=Ziegeler}
                                {id=2, title=JCR, speaker=Ziegeler}
                                {id=3, title=Portals, speaker=Ziegeler}


                                                                    36
Map Results Inline
• Inline definition

  <select id=quot;getAllSessionsquot; resultClass=quot;java.util.HashMapquot;>
   SELECT id, title, speaker_name   speaker
   FROM sessions_t
  </select>



                           sqlmap.queryForList(quot;getAllSessionsquot;)

                           {id=1, title=iBatis, speaker=Ziegeler}
                           {id=2, title=JCR, speaker=Ziegeler}
                           {id=3, title=Portals, speaker=Ziegeler}



                                                               37
Parameters and Results
    Primitive types
•
    Maps
•
•   Beans
•   Inline or extra definition
•   Quick Start: Maps + primitive types inline
Using the Data Mapper
• Lightweight API
  – Configuration
  – Executing Queries
  – Updating (inserts and deletes)
  Reader reader = Resources.getResourceAsReader
               (quot;samples/sql-map-config.xmlquot;);

  SqlMapClient sqlMap =
              SqlMapClientBuilder.buildSqlMapClient(reader);




                                                     39
Queries
• Single objects: sqlMap.queryForObject()
• Lists: sqlMap.queryForList()
• Maps: sqlMap.queryForMap()
  – Key can be any mapped property
• Each query is run with:
  – Configured map identifier
  – Parameters (optional)
             sqlmap.queryForList(quot;getAllSessionsquot;)

             {id=1, title=iBatis, speaker=Ziegeler}
                                                       40
             {id=2, title=JCR, speaker=Ziegeler}
             {id=3, title=Portals, speaker=Ziegeler}
Updates, Inserts and Deletes
• sqlMap.update(quot;updatePersonquot;, person);
• sqlMap.insert(quot;insertPersonquot;, person);
• sqlMap.delete(quot;deletePersonquot;, 5);




                                       41
Additional Features
    Mapping relationships
•
    Joins
•
•   Lazy loading
•   Transactions, Batches
•   Stored Procedures
•   Caching
•   And more…
                                 42
Fragments
• Define fragments for reuse
   – Avoid duplicate definitions
<sql id=quot;base-selectquot;>
   SELECT id as personID
   ,      ...
   FROM person_t pers
</sql>

<select id=quot;getPersonquot; resultClass=quot;personquot; parameterClass=quot;longquot;>
  <include refid=quot;base-selectquot;/>
  WHERE pers.id = #value#
</select>
<select id=quot;getPersonsquot; resultClass=quot;personquot;>
  <include refid=quot;base-selectquot;/>
  ORDER BY date_of_birth   ASC
</select>

                                                           43
Dynamic SQL Statements
• Dynamic statements (if …)
• Using parameters:
 <select id=quot;findPersonsquot; resultMap=“personquot;
         parameterClass=quot;java.util.Mapquot;>
   SELECT id, first_name, last_name FROM person_t pers
   WHERE category = #category#
   $whereclause$
   ORDER BY $orderlist$
 </select>
                Map paramMap = new HashMap();
                paramMap.put(quot;categoryquot;, quot;Businessquot;));
                paramMap.put(quot;whereclausequot;, quot;and id > 10quot;);
                paramMap.put(quot;orderlistquot;, quot;date_of_birtsh DESCquot;);

                sqlmap.queryForList(quot;findPersonsquot;, paramMap);


                                                            44
Apache iBatis
    Quick Intro
•
    Quick Start Guide
•
•   The Data Mapping
•   The Database Configuration
•   Summary



                                 45
Data Base Configuration
• Central XML configuration
  – Properties
  – Data source
          <sqlMapConfig>
            <properties/>
            <settings/>
            <typeAlias/> *

            <transactionManager>
               <dataSource/>
            </transactionManager>

            <sqlMap/> *
          </sqlMapConfig>

                                    46
Configuration Properties
• Properties can be loaded from
  – The classpath: <properties resource=quot;quot;/>
  – URL: <properties url=quot;quot;/>
• Values can be referenced with Ant style
  syntax: ${key}




                                               47
Transaction Manager
• Transaction manager
  • JDBC
  • JTA
  • EXTERNAL

 <transactionManager type=quot;JDBCquot;>
      <dataSource …




                                    48
Data Source
• Data source factory and properties
  – SIMPLE – based on iBATIS connection
    pooling implementation
  – DBCP – uses Jakarta DBCP
  – JNDI – retrieves data source from a JNDI
    context
  – Own factories possible


                                               49
Data Source Sample
• Data source factory and properties
   <dataSource type=quot;SIMPLEquot;>
     <property value=quot;${driver}quot; name=quot;JDBC.Driverquot; />
     <property value=quot;${url}quot; name=quot;JDBC.ConnectionURLquot; />
     <property value=quot;${username}quot; name=quot;JDBC.Usernamequot; />
     <property value=quot;${password}quot; name=quot;JDBC.Passwordquot; />
   </dataSource>




                                                      50
SQL Maps Configuration
• All SQL Map files must be referenced
   – Classpath
   – URL
<sqlMap resource=quot;samples/Person.xmlquot; />
<sqlMap url=quot;file:///d:/ibatis/Person.xmlquot; />




                                                51
Apache iBatis
    Quick Intro
•
    Quick Start Guide
•
•   The Data Mapping
•   The Database Configuration
•   Summary



                                 52
Apache iBatis
• Easy and quick start
• Mapping Java beans to SQL at the SQL
  level
• XML configuration files for mapping and
  db config
• Very good documentation!
• Check it out!

                                       53
Thanks
 Q&A

Visit our booth for
infos, discussions
and jobs!

Más contenido relacionado

La actualidad más candente

Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Understanding
Understanding Understanding
Understanding
Arun Gupta
 

La actualidad más candente (20)

Basic JSTL
Basic JSTLBasic JSTL
Basic JSTL
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Simplifying JavaScript Projects with ReactJS
Simplifying JavaScript Projects with ReactJSSimplifying JavaScript Projects with ReactJS
Simplifying JavaScript Projects with ReactJS
 
Jdbc
JdbcJdbc
Jdbc
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
MongoDB & NoSQL 101
 MongoDB & NoSQL 101 MongoDB & NoSQL 101
MongoDB & NoSQL 101
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
 
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und HibernateEffiziente Datenpersistierung mit JPA 2.1 und Hibernate
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Rapid Prototyping with PEAR
Rapid Prototyping with PEARRapid Prototyping with PEAR
Rapid Prototyping with PEAR
 
Understanding
Understanding Understanding
Understanding
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
 
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?
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Hibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic IntroductionHibernate working with criteria- Basic Introduction
Hibernate working with criteria- Basic Introduction
 

Similar a Apache Con Us2007 Apachei Batis

Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
Gunith Devasurendra
 
Wide Open Spaces Using My Sql As A Web Mapping Service Backend
Wide Open Spaces Using My Sql As A Web Mapping Service BackendWide Open Spaces Using My Sql As A Web Mapping Service Backend
Wide Open Spaces Using My Sql As A Web Mapping Service Backend
MySQLConference
 

Similar a Apache Con Us2007 Apachei Batis (20)

Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
Rapidly Building Data Driven Web Pages with Dynamic ADO.NET
Rapidly Building Data Driven Web Pages with Dynamic ADO.NETRapidly Building Data Driven Web Pages with Dynamic ADO.NET
Rapidly Building Data Driven Web Pages with Dynamic ADO.NET
 
BDD in iOS with Cedar
BDD in iOS with CedarBDD in iOS with Cedar
BDD in iOS with Cedar
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your database
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your database
 
Visualizing Web Data Query Results
Visualizing Web Data Query ResultsVisualizing Web Data Query Results
Visualizing Web Data Query Results
 
WWW2012 Tutorial Visualizing SPARQL Queries
WWW2012 Tutorial Visualizing SPARQL QueriesWWW2012 Tutorial Visualizing SPARQL Queries
WWW2012 Tutorial Visualizing SPARQL Queries
 
Tutorial On Database Management System
Tutorial On Database Management SystemTutorial On Database Management System
Tutorial On Database Management System
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices -  Michael HacksteinNoSQL meets Microservices -  Michael Hackstein
NoSQL meets Microservices - Michael Hackstein
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
I Feel Pretty
I Feel PrettyI Feel Pretty
I Feel Pretty
 
Boston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesBoston Computing Review - Java Server Pages
Boston Computing Review - Java Server Pages
 
Wide Open Spaces Using My Sql As A Web Mapping Service Backend
Wide Open Spaces Using My Sql As A Web Mapping Service BackendWide Open Spaces Using My Sql As A Web Mapping Service Backend
Wide Open Spaces Using My Sql As A Web Mapping Service Backend
 

Más de day

Performance Pack
Performance PackPerformance Pack
Performance Pack
day
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
day
 
Scala4sling
Scala4slingScala4sling
Scala4sling
day
 
Testing Zen
Testing ZenTesting Zen
Testing Zen
day
 
Java Persistence Frameworks
Java Persistence FrameworksJava Persistence Frameworks
Java Persistence Frameworks
day
 
Embrace OSGi Apache Con Europe2009
Embrace OSGi Apache Con Europe2009Embrace OSGi Apache Con Europe2009
Embrace OSGi Apache Con Europe2009
day
 
Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3
day
 
Tarpm Clustering
Tarpm ClusteringTarpm Clustering
Tarpm Clustering
day
 
Tech Summit 08 Support Initiative
Tech Summit 08 Support InitiativeTech Summit 08 Support Initiative
Tech Summit 08 Support Initiative
day
 
Non Cms For Web Apps
Non Cms For Web AppsNon Cms For Web Apps
Non Cms For Web Apps
day
 
Getting Into The Flow With Cq Dam
Getting Into The Flow With Cq DamGetting Into The Flow With Cq Dam
Getting Into The Flow With Cq Dam
day
 
Dispatcher Oom
Dispatcher OomDispatcher Oom
Dispatcher Oom
day
 
Advanced Collaboration And Beyond
Advanced Collaboration And BeyondAdvanced Collaboration And Beyond
Advanced Collaboration And Beyond
day
 
Wc Mand Connectors2
Wc Mand Connectors2Wc Mand Connectors2
Wc Mand Connectors2
day
 
Jackrabbit Roadmap
Jackrabbit RoadmapJackrabbit Roadmap
Jackrabbit Roadmap
day
 
Doc Book Vs Dita
Doc Book Vs DitaDoc Book Vs Dita
Doc Book Vs Dita
day
 
Doc Book Vs Dita Teresa
Doc Book Vs Dita TeresaDoc Book Vs Dita Teresa
Doc Book Vs Dita Teresa
day
 
862
862862
862
day
 
Apache Con Us2007 Sanselan
Apache Con Us2007 SanselanApache Con Us2007 Sanselan
Apache Con Us2007 Sanselan
day
 
Apache Con Us2007 Jcr In Action
Apache Con Us2007 Jcr In ActionApache Con Us2007 Jcr In Action
Apache Con Us2007 Jcr In Action
day
 

Más de day (20)

Performance Pack
Performance PackPerformance Pack
Performance Pack
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
Scala4sling
Scala4slingScala4sling
Scala4sling
 
Testing Zen
Testing ZenTesting Zen
Testing Zen
 
Java Persistence Frameworks
Java Persistence FrameworksJava Persistence Frameworks
Java Persistence Frameworks
 
Embrace OSGi Apache Con Europe2009
Embrace OSGi Apache Con Europe2009Embrace OSGi Apache Con Europe2009
Embrace OSGi Apache Con Europe2009
 
Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3Scripting Yor Java Application with BSF3
Scripting Yor Java Application with BSF3
 
Tarpm Clustering
Tarpm ClusteringTarpm Clustering
Tarpm Clustering
 
Tech Summit 08 Support Initiative
Tech Summit 08 Support InitiativeTech Summit 08 Support Initiative
Tech Summit 08 Support Initiative
 
Non Cms For Web Apps
Non Cms For Web AppsNon Cms For Web Apps
Non Cms For Web Apps
 
Getting Into The Flow With Cq Dam
Getting Into The Flow With Cq DamGetting Into The Flow With Cq Dam
Getting Into The Flow With Cq Dam
 
Dispatcher Oom
Dispatcher OomDispatcher Oom
Dispatcher Oom
 
Advanced Collaboration And Beyond
Advanced Collaboration And BeyondAdvanced Collaboration And Beyond
Advanced Collaboration And Beyond
 
Wc Mand Connectors2
Wc Mand Connectors2Wc Mand Connectors2
Wc Mand Connectors2
 
Jackrabbit Roadmap
Jackrabbit RoadmapJackrabbit Roadmap
Jackrabbit Roadmap
 
Doc Book Vs Dita
Doc Book Vs DitaDoc Book Vs Dita
Doc Book Vs Dita
 
Doc Book Vs Dita Teresa
Doc Book Vs Dita TeresaDoc Book Vs Dita Teresa
Doc Book Vs Dita Teresa
 
862
862862
862
 
Apache Con Us2007 Sanselan
Apache Con Us2007 SanselanApache Con Us2007 Sanselan
Apache Con Us2007 Sanselan
 
Apache Con Us2007 Jcr In Action
Apache Con Us2007 Jcr In ActionApache Con Us2007 Jcr In Action
Apache Con Us2007 Jcr In Action
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Apache Con Us2007 Apachei Batis

  • 1. Apache iBatis Getting Up to Speed Carsten Ziegeler cziegeler@apache.org Day Software
  • 2. About Carsten Ziegeler • Apache Software Foundation Member – Cocoon, Excalibur, Pluto, Felix, Incubator, Sling, Sanselan – PMC: Cocoon, Incubator, Portals, Felix, Excalibur (Chair) • Senior Developer at Day Software • Article/Book Author, Technical Reviewer • JSR 286 spec group (Portlet API 2.0)
  • 3. and jobs! infos, discussions Visit our booth for Apache iBatis Quick Intro • Quick Start Guide • • The Data Mapping • The Database Configuration • Summary 3
  • 4. A Common Problem Reading from / writing to a database in Java • Mapping of result sets to objects • • Mapping of objects to tables/columns • Object Relational Mapping (ORM) 4
  • 5. Why do I need iBatis? • Several ORM solutions out there – Hibernate, Apache OpenJPA, Apache OJB – Very sophisticated, but quot;heavyquot; solutions – Usable for literally everything – Setting up, configuring, using takes time • What about javax.sql/JDBC? – ….if you think that SQL and Java code mixes well 5
  • 6. Why do I need iBatis? • Apache iBatis fits in-between – Small library – Simple setup – Easy to use – Uses data maps 6
  • 7. Use the Right Tool! • Not every tool is suited for every use case! – Analyze requirements – Decide for the tool – Constantly check decision • Apache iBatis is not suited for all ORM problems 7
  • 8. Some Typical Scenarios for iBatis • Reading dictionaries (like i18n translations) • Performing complex and nested queries – Full SQL support • Reading configuration • Writing log statements • Displaying query results 8
  • 9. The Project • Popular tool – Abstracting JDBC – Working at the SQL level • Started by Clinton Begin – Part of Apache since 2005 – Top level project • Current version 2.x (> 3 years old) – Next major version in design discussions 9
  • 10. The Project • Two frameworks – iBatis Data Mapper – iBatis Data Access Objects • Implementations for different languages – Java, .Net, Ruby/Rails • Focus on the Java Data Mapper 10
  • 11. How Does it Work? SQL statements are defined in XML • Statements can contain placeholders • • Placeholders are replaced on execution • SQL query result is mapped to objects 11
  • 12. Some Advantages • Retain the full power of SQL – Functions like avg, sum, count etc. – Mapping across tables • Single point of configuration • Short integration time • Very good documentation • Caching of query results 12
  • 13. Caveats No transparent persistence • No change detection • • Explicit mapping required • No implicit operations (like cascaded updates, deletes etc.) 13
  • 14. Installation • Download and add to classpath • Optional 3rd party jars for additional stuff – Refer to the documentation File Name Description Required ibatis-common.jar iBATIS Common Utilities YES ibatis-sqlmap.jar iBATIS Data Mapper Framework YES ibatis-dao.jar iBATIS Data Access Framework NO 14
  • 16. Apache iBatis Quick Intro • Quick Start Guide • • The Data Mapping • The Database Configuration • Summary 16
  • 17. Four Basic Steps 1. Write Java beans (optional) 2. Create mapping configuration 3. Specify the SQL configuration 4. Write the app code executing the statements 17
  • 18. 1. Write Java Beans (optional) • Use primitive types for properties • Alternative: maps Person.java public class Person { private long personId; private String name; private java.util.Date dateOfBirth; // getters and setters: ... 18
  • 19. 2. Create Mapping Configuration Person.xml <sqlMap namespace=quot;Personquot;> <select id=quot;getPersonquot; resultClass=quot;samples.Personquot; parameterClass=quot;longquot;> SELECT id as personId , p_name as name , date_of_birth as dateOfBirth FROM person_t pers WHERE pers.id = #value# </select> </sqlMap> 19
  • 20. 3. Specify the SQL Configuration sql-map-config.xml <sqlMapConfig> <transactionManager type=quot;JDBCquot;> <dataSource type=quot;SIMPLEquot;> <property ... ... </dataSource> </transactionManager> <sqlMap resource=quot;samples/maps/Person.xmlquot;/> </sqlMapConfig> 20
  • 21. 4. Write the App Code DAO.java public Person getPerson(long id) { Person p = null; try { // Configure iBatis Reader reader = Resources.getResourceAsReader (quot;samples/sql-map-config.xmlquot;); SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); // execute p = (Person)sqlMap.queryForObject(quot;getPersonquot;, id); } catch (Exception e) { // do something useful here } return p; } 21
  • 22. Apache iBatis Quick Intro • Quick Start Guide • • The Data Mapping • The Database Configuration • Summary 22
  • 23. The Data Mapping • Define mapping between Java objects and SQL • XML configuration file(s) • iBatis offers many possibilities/features – The following is just an overview – Check out the docs – (Often maps are sufficient)
  • 24. Mapping Elements • Mapping Java beans to SQL statements • More than one config file possible <sqlMap> <typeAlias/> * <parameterMap/> * <resultMap/> * <statement/> * <select | insert | update | delete | procedure/> * </sqlMap> 24
  • 25. Data Mapper Concept • Mapped statements – SQL – Parameter maps (input) – Result maps (output) <select id=quot;getAllUsersquot; resultMap=quot;Userquot;> SELECT id, username, password, active FROM user_t </select> 25
  • 26. Querying the Database • Unique identifier • Result and parameter class • SQL statements (it's XML!) <select id=quot;getOlderThanquot; resultClass=quot;Personquot; parameterClass=quot;datequot;> <![CDATA[ SELECT id as personID , ... FROM person_t pers WHERE date_of_birth > #value# ]]> </select> 26
  • 27. Parameters: Primitive Types • Primitive types can directly be used for input – e.g. String, Integer, Date, etc. – #value# references the actual value <statement id=quot;getPersonquot; parameterClass=quot;java.lang.Integerquot;> SELECT * FROM product_t WHERE product_id = #value# </statement> sqlMapClient.queryForObject(quot;getPersonquot;, new Integer(1)); 27
  • 28. Parameters: Beans • Mapping description: bean -> input – Properties – Optional type definition: Java and JDBC – Optional null values – Optional type handler for conversion <parameterMap id=quot;parameterMapNamequot; [class=quot;someDomainClassquot;]> <parameter property=quot;propertyNamequot; [jdbcType=quot;VARCHARquot;] [javaType=quot;stringquot;] [nullValue=quot;-1quot;] [typeHandler=quot;someHandlerquot;]/> <parameter .../> </parameterMap> 28
  • 29. Parameters: Beans • Properties are applied in order of definition <parameterMap id=quot;personMapquot; class=quot;samples.Personquot;> <parameter property=quot;namequot;/> <parameter property=quot;dateOfBirthquot;/> <parameter property=quot;addressquot;/> </parameterMap> <insert id=quot;insertPersonquot; parameterMap=quot;personMapquot;> INSERT INTO person_t (name, date_of_birth, address) VALUES (?, ?, ?) </insert> 29
  • 30. Parameters: Inline Beans • Less verbose form of parameter maps – Inline property names <insert id=quot;insertPersonquot; parameterMap=quot;samples.Personquot;> INSERT INTO person_t (name, date_of_birth, address) VALUES (#name#, #dateOfBirth#, #address#) </insert> 30
  • 31. Parameters: Inline Beans • Support for types and null values <insert id=quot;insertPersonquot; parameterMap=quot;samples.Personquot;> INSERT INTO person_t (name, date_of_birth, address) VALUES (#name#, #dateOfBirth#, #address:VARCHAR:NO_ADDR#) </insert> 31
  • 32. Parameters: Maps • Alternative to custom beans: maps – java.util.HashMap etc. – #key# references the value stored for key <statement id=quot;getAddressesquot; parameterClass=quot;java.util.Mapquot;> SELECT * FROM addresses_t WHERE person_id = #personID# AND category_information = #category# </statement> params.put(quot;personIDquot;, new Integer(1)); params.put(quot;categoryquot;, quot;Businessquot;); sqlMapClient.queryForList(quot;getAddressesquot;, params); 32
  • 33. Result Maps • Mapping result sets to beans – Properties/columns – Optional type definition: Java and JDBC – Optional null values – Optional type handler for conversion <resultMap id=quot;resultMapNamequot; class=quot;someDomainClassquot; [extends=quot;parent-resultMapquot;]> <result property=quot;propertyNamequot; column=quot;COLUMN_NAMEquot; [javaType=quot;intquot;] [jdbcType=quot;NUMERICquot;] [nullVlaue=quot;-1quot;] [typeHandler=quot;someHandlerquot;]/> <result .../> </resultMap> 33
  • 34. Result Maps: Inline • Direct mapping <select id=quot;getPersonquot; parameterClass=quot;longquot; resultClass=quot;samples.Personquot;> SELECT id AS personID , first_name AS firstName , email , ... FROM person_t pers WHERE pers.id = #value# public class Person { </select> private long personID; private String firstName; private String email; ... 34
  • 35. Primitive Results • Primitive types can directly be used – e.g. String, Integer, Date, etc. – Result map or inline <resultMap id=quot;get-resultquot; resultClass=quot;java.lang.Integerquot;> <result property=quot;valuequot; column=quot;NUMBER_OF_CUSTOMERSquot;/> </resultMap> <statement id=quot;getPersonCountquot; resultClass=quot;intquot; SELECT count(*) AS value FROM person_t </statement> 35
  • 36. Map Results • Alternative to custom beans: maps – java.util.HashMap etc. <resultMap id=quot;result-mapquot; resultClass=quot;java.util.HashMapquot;> <result property=quot;idquot; column=quot;IDquot;/> <result property=quot;titlequot; column=quot;TITLEquot;/> <result property=quot;speakerquot; column=quot;SPEAKER_NAMEquot;/> </resultMap> <select id=quot;getAllSessionsquot; resultMap=quot;result-mapquot;> SELECT id, title, speaker_name FROM sessions_t </select> sqlmap.queryForList(quot;getAllSessionsquot;) {id=1, title=iBatis, speaker=Ziegeler} {id=2, title=JCR, speaker=Ziegeler} {id=3, title=Portals, speaker=Ziegeler} 36
  • 37. Map Results Inline • Inline definition <select id=quot;getAllSessionsquot; resultClass=quot;java.util.HashMapquot;> SELECT id, title, speaker_name speaker FROM sessions_t </select> sqlmap.queryForList(quot;getAllSessionsquot;) {id=1, title=iBatis, speaker=Ziegeler} {id=2, title=JCR, speaker=Ziegeler} {id=3, title=Portals, speaker=Ziegeler} 37
  • 38. Parameters and Results Primitive types • Maps • • Beans • Inline or extra definition • Quick Start: Maps + primitive types inline
  • 39. Using the Data Mapper • Lightweight API – Configuration – Executing Queries – Updating (inserts and deletes) Reader reader = Resources.getResourceAsReader (quot;samples/sql-map-config.xmlquot;); SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); 39
  • 40. Queries • Single objects: sqlMap.queryForObject() • Lists: sqlMap.queryForList() • Maps: sqlMap.queryForMap() – Key can be any mapped property • Each query is run with: – Configured map identifier – Parameters (optional) sqlmap.queryForList(quot;getAllSessionsquot;) {id=1, title=iBatis, speaker=Ziegeler} 40 {id=2, title=JCR, speaker=Ziegeler} {id=3, title=Portals, speaker=Ziegeler}
  • 41. Updates, Inserts and Deletes • sqlMap.update(quot;updatePersonquot;, person); • sqlMap.insert(quot;insertPersonquot;, person); • sqlMap.delete(quot;deletePersonquot;, 5); 41
  • 42. Additional Features Mapping relationships • Joins • • Lazy loading • Transactions, Batches • Stored Procedures • Caching • And more… 42
  • 43. Fragments • Define fragments for reuse – Avoid duplicate definitions <sql id=quot;base-selectquot;> SELECT id as personID , ... FROM person_t pers </sql> <select id=quot;getPersonquot; resultClass=quot;personquot; parameterClass=quot;longquot;> <include refid=quot;base-selectquot;/> WHERE pers.id = #value# </select> <select id=quot;getPersonsquot; resultClass=quot;personquot;> <include refid=quot;base-selectquot;/> ORDER BY date_of_birth ASC </select> 43
  • 44. Dynamic SQL Statements • Dynamic statements (if …) • Using parameters: <select id=quot;findPersonsquot; resultMap=“personquot; parameterClass=quot;java.util.Mapquot;> SELECT id, first_name, last_name FROM person_t pers WHERE category = #category# $whereclause$ ORDER BY $orderlist$ </select> Map paramMap = new HashMap(); paramMap.put(quot;categoryquot;, quot;Businessquot;)); paramMap.put(quot;whereclausequot;, quot;and id > 10quot;); paramMap.put(quot;orderlistquot;, quot;date_of_birtsh DESCquot;); sqlmap.queryForList(quot;findPersonsquot;, paramMap); 44
  • 45. Apache iBatis Quick Intro • Quick Start Guide • • The Data Mapping • The Database Configuration • Summary 45
  • 46. Data Base Configuration • Central XML configuration – Properties – Data source <sqlMapConfig> <properties/> <settings/> <typeAlias/> * <transactionManager> <dataSource/> </transactionManager> <sqlMap/> * </sqlMapConfig> 46
  • 47. Configuration Properties • Properties can be loaded from – The classpath: <properties resource=quot;quot;/> – URL: <properties url=quot;quot;/> • Values can be referenced with Ant style syntax: ${key} 47
  • 48. Transaction Manager • Transaction manager • JDBC • JTA • EXTERNAL <transactionManager type=quot;JDBCquot;> <dataSource … 48
  • 49. Data Source • Data source factory and properties – SIMPLE – based on iBATIS connection pooling implementation – DBCP – uses Jakarta DBCP – JNDI – retrieves data source from a JNDI context – Own factories possible 49
  • 50. Data Source Sample • Data source factory and properties <dataSource type=quot;SIMPLEquot;> <property value=quot;${driver}quot; name=quot;JDBC.Driverquot; /> <property value=quot;${url}quot; name=quot;JDBC.ConnectionURLquot; /> <property value=quot;${username}quot; name=quot;JDBC.Usernamequot; /> <property value=quot;${password}quot; name=quot;JDBC.Passwordquot; /> </dataSource> 50
  • 51. SQL Maps Configuration • All SQL Map files must be referenced – Classpath – URL <sqlMap resource=quot;samples/Person.xmlquot; /> <sqlMap url=quot;file:///d:/ibatis/Person.xmlquot; /> 51
  • 52. Apache iBatis Quick Intro • Quick Start Guide • • The Data Mapping • The Database Configuration • Summary 52
  • 53. Apache iBatis • Easy and quick start • Mapping Java beans to SQL at the SQL level • XML configuration files for mapping and db config • Very good documentation! • Check it out! 53
  • 54. Thanks Q&A Visit our booth for infos, discussions and jobs!