SlideShare a Scribd company logo
Crash Introduction to
Modern Java Data Access:
Understanding JPA, Hibernate,
MyBatis, and pureQuery
Dr. Vladimir Bacvanski

Session Code: E13
May 6, 2011 * 8:00 – 9:00am | Platform: Cross Platform
Outline
•   Database/Programming Languages Chasm
•   Persistence Options
    P i t       O ti
•   JDBC
•   Object R l ti
    Obj t Relational M
                     l Mapping
                           i
•   JPA & Hibernate
•   MyBatis
•   pureQuery
•   Conclusions


                                           2
Database/Programming Languages Chasm
            g      g    g g
• Relational Database                        • Java
           Customer                                     c1: Customer
    id  name p
             phone  email                        name="Joe"
    1      Joe        123‐…      
    joe@...                                      phone=123‐ 456‐7890
                                                 phone=123 456 7890
                                                 email="joe@xyz.com"


            Address
            Add
    custId street                     city
                                         y               a1: Address
    1               1 Nice …                     street="1 Nice Way"
    San…
    San
                                                 city="San Francisco"

  • The world consists of                      • The world consists of
    tables                                       objects, which are
                                                 instances of classes    3
Accessing Databases: Many Choices!
        g               y

      pureQuery                                          JDBC



                                                             SQLJ
    MyBatis
    (iBatis)
           )
                                                      Hibernat
                                                         e

               JPA                         EJB

                There are more choices, but we'll discuss just the more popular ones
                                                                                       4
JDBC
• JDBC (Java Database Connectivity) provides an API
  allowing for explicit creation of SQL queries from Java
• The API allows for issuing of SQL commands
   • Prepared queries
   • Ad-hoc queries
   • Callable statements
• The result comes back as a cursored table




                                                            5
Code Example: JDBC
           p
java.sql.PreparedStatement ps =        Table       Column      Type
con.prepareStatement(                  EMP         NAME        CHAR(64)

        "SELECT NAME, ADDRESS,         EMP         ADDRESS     CHAR(128)
         PHONE_NUM FROM EMP 
                                       EMP         PHONE_NUM   CHAR(10)
         WHERE NAME=?");
ps.setString(1, name);
java.sql.ResultSet rs = ps.executeQuery();
rs.next();
       ();
Employee myEmp = new Employee();
myEmp.setName(rs.getString(1));          class Employee {
myEmp.setHomeAddress(rs.getString(2));
myEmp setHomeAddress(rs getString(2));       public String name;
                                             public String name;
                                             public String homeAddress;
myEmp.setHomePhone(rs.getString(3));
                                             public String homePhone;
rs.close();                                  …
                                           }

                                                                           6
Issues with Plain JDBC
• Benefits
   • Performance
      • It is possible to write optimized queries for a particular task
      • It is possible to take advantage of underlying DB capabilities
   • Ease of debugging
      • The connection between the DB and application code is clear
• Drawbacks
   • Cumbersome programming
      • The mapping from the application world (Java objects) to the DB
        world may be cumbersome and complex
      • Much code may have to be written and debugged
      • It is easy to introduce mechanical bugs
             • E.g., closing of connections
   • JDBC API lags behind modern database features                        7
Object-Relational Mapping
  j                 pp g
• Issues with JDBC led to development of O/R mapping,
  most notably Hibernate as the leading implementation
• One popular approach to connect applications to the
  database is the use of an object-relational mapping tool
  (ORM)
• Many ORM technologies and implementations available:
   • JPA: The dominant specification
   • Hibernate, OpenJPA, EclipseLink: JPA implementations




                                                             8
Mapping Between the Worlds
  pp g
                         <<enumeration>>
                            BikeType

                        RACING
                        MOUNTAIN
                        STREET
                        UNICYCLE
                                                                                  Vehicle           vehiclePark                owner             Person

                                                                           name: String                                                    name: String
                                                                                                     *                              1


                        MotorizedVehicleType                                                          *                             *
                      name: String                                                                 availableCars            legalUsers
                      description: String


                                1     type
                                                                                                                                                        *
                                             instances     MotorizedVehicle                        Bike
                                                          fuelCapacity: Integer         bikeType: BikeType                                      Address
                                                  *
                                                                                                                                           street: String
                                                                                                                                           city: String
                                                                                                                                           state: String
                                                                                                                                           country: String




                           MOTORIZED_VEHICLE_TYPE                                 VEHICLE_2_PERSON_MAP                                   PERSON_TBL

                           PK id               char(10)                    PK,FK2 legal_driver_id          char (10)           PK id            char (10)
                                                                           PK,FK1 available _car_id        char (10)
                                 name        varchar (50)                                                                                name   varchar (50)
                                 description varchar(255)




                                                                        VEHICLE_TBL

                                                               PK     id            char(10)

                                                               FK1 owner_id         char(10)
                                                                   name             varchar (50)
                                                                   type             smallint

                                                                                                                                        ADDRESS_TBL

                                                                                                                          PK   id                varchar (16)
                                     MOTORIZED_VEHICLE_TBL                                         BIKE_TBL               FK1 occupant _id       char(10)
                             PK,FK1,FK2 id                          char(10)          PK,FK1 id                char(10)       street             varchar (250)
                                                                                                                              city               varchar (50)
                                              fuel_consumption real                                bike_type   smallint       state              varchar (50)
                                              type_id          char(10)                                                       country            varchar (40)


                                                                                                                                                                 9
JPA Example: Annotations
        p
@Entity
public class Employee {
    @Id
    private Long id;


    @ManyToOne
    private Department department;
    ...
}


@Entity
@   i
public class Department {
    @OneToMany(mappedBy="department")
    private Collection<Employee> employees = new HashSet();
                                                              10
JPA Inheritance Example
                    p
@Entity
@
@Inheritance
@DiscriminatorColumn(
   name="DISC", discriminatorType=STRING,length=20)
@DiscriminatorValue( PERSON )
@DiscriminatorValue(“PERSON")
public class Person { ... }


@Entity
@DiscriminatorValue("CUSTOMER")
p
public class Customer extends Person { ... }
                                     {     }




                                                      11
Hibernate: More than JPA
• JPA was heavily inspired by Hibernate
• T d
  Today, Hib
         Hibernate i l
                t implements th JPA standard
                             t the      t d d
• Provides more features in areas:
   •   Primary k generators
       Pi        key        t
   •   Control over cascade behaviors
   •   Criteria for query building
   •   Query language HQL
   •   Caching
   •   …



                                                12
Issues with ORM Tools
• Benefits
   • Ease of use for the application programmer
      • The programmer writes code assuming an object model
      • The tool maps the object model to SQL
   • Continuity
      • The domain model (from analysis) is preserved in implementation
• Drawbacks
   • Performance
      • It is hard for the general p p
                           g       purpose mapping tool to take advantage of
                                             pp g                      g
        the underlying database capabilities
   • Complex to debug
      • The mapping can make finding errors very hard

                                                                               13
MyBatis (iBatis)
 y      (      )
•   MyBatis was earlier known as iBatis
•   SQL is fully exposed: MyBatis is not a full ORM!
               y p         y
•   Persistence access is explicit through SQL
•   Reduced Java boilerplate code in comparison with JDBC

                           Mapping
                       XML or Annotations
       Input                                        Output

     Hashtable                                     Hashtable
                            Mapped 
                            Mapped
       POJO                Statement                  POJO

     Primitive                                      Primitive
                                                                14
SQL Mapping and Call in MyBatis
 Q    pp g               y
Mapping:
<?xml version 1.0 encoding="UTF‐8" ?>
<?xml version="1.0" encoding UTF 8  ?>
<!DOCTYPE mapper PUBLIC "‐//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis‐3‐mapper.dtd">
<mapper namespace="com.scispike.CustomerMapper">
        namespace com.scispike.CustomerMapper >
   <select id="selectCustomer" parameterType="int"
      resultType="Customer">
        select  from Customer where id = #{id}
        select * from Customer where id = #{id}
   </select>
</mapper>


Call:
Customer cust = (Customer) session.selectOne(
  "com.scispike.CustomerMapper.selectCustomer", 1001);

                                                               15
Issues with MyBatis
             y
• Benefits
   • Full control over SQL and improved productivity in comparison
     with JDBC
   • Suitable for dealing with legacy databases
   • Troubleshooting easier in comparison with JPA


• D
  Drawbacks
      b k
   • Tooling support is lacking
   • Productivity initially reduced in comparison with JPA but catches
                                                       JPA,
     up later through easier troubleshooting



                                                                         16
p
pureQuery
    Q   y
• A high-performance, data access platform to simplify
  developing, managing, securing,
  developing managing securing and optimizing data
  access
pureQuery Components:
• Simple and intuitive API
  • Enables SQL access to databases or in-memory Java objects
                                                  y      j
  • Facilitates best practices
• Optim Development Studio (integrates with RAD/RSA)
  • Integrated development environment with Java and SQL support
  • Improve problem isolation and impact analysis
  • Optimize existing code: JDBC/JPA/Hibernate/MyBatis
• Optim pureQuery Runtime
  • Flexible static SQL deployment for DB2
                                                                   17
Code Example: pureQuery
         p p      Q   y
• "Inline" query:

  Employee myEmp = db.queryFirst(
       "SELECT NAME, ADDRESS, PHONE_NUM FROM EMP
        WHERE NAME=?", Employee.class, name);
                   ?"     l      l         )


• Even simpler, if we have a method getEmployee with a
       simpler
  Java annotation or XML file with SQL for the query:

  Employee myEmp = db.getEmployee(name);



                                                         18
Optim Development Studio: pureQuery IDE
 p          p             p   Q   y




                            Visualize
                         application SQL
       Replace SQL
       R l
                                             Visualize execution
    without changing
                                                   metrics
     the application




   Position i
   P iti in
Database Explorer                         Execute, tune,
                                       share, trace, explore       19
                                                SQL
SQL Integration with Java
 Q      g
• SQL content assist




• SQL validation
        lid ti




                            20
Data Access Objects – pureQuery support
              j       p   Q   y pp
Quickly create JEE Data Access Objects
• A i t f
  An interface with only your methods
                 ith l           th d
• Methods for each database access
• E h method h only your parameters
  Each     th d has l                 t
• SQL can be in XML file or annotations
• Implementation automatically generated with best practice
  database access and optimizations.
• T
  Template-based generation with t
        l t b     d        ti   ith template customization
                                        l t     t i ti
• Mix hand-written and generated code.
   • C modify generated code and safely regenerate.
     Can dif        t d d      d f l            t
                                                          21
p
 pureQuery: Optimal Productivity and Control
     Q   y p                   y

       Full SQL Control       Object-Relational Mapping                 Managed Objects

                Code all your SQL

JDBC / SQLJ


  MyBatis
                Add basic OR mapping and annotated-method style
pureQuery
                                    Complex O/R mapping and persistence management, but loss of control
                                       p          pp g      p               g
JPA/Hibernate
                                                       Adds container management option
   EJB 3


                                                                                                   22
Conclusion
• Each approach has its strengths and weaknesses
• JDBC alone
         l
   • To low level for most applications
• JPA and Hibernate
   • Good choice when you own the database, performance not critical
• MyBatis
   • Full control over SQL, reduced boilerplate
• pureQuery
   • Full control over SQL , mixing productivity, static SQL, and
     integrated tooling

                                                                    23
Getting in Touch
      g
•   Email: vladimir.bacvanski@scispike.com
•   Blog: htt //
    Bl    http://www.OnBuildingSoftware.com/
                        O B ildi S ft          /
•   Twitter: http://twitter.com/OnSoftware
•   LinkedIn: http://www.linkedin.com/in/VladimirBacvanski
    Li k dI htt //           li k di   /i /Vl di i B    ki



• Parts of the presentation are from SciSpike courses:
    •   Developing Database Applications with Optim Development Studio and pureQuery
    •   Hibernate




                                                                                   24

More Related Content

Viewers also liked (20)

PPTX
Top 50 java ee 7 best practices [con5669]
Ryan Cuprak
 
PPTX
50 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
Ryan Cuprak
 
PDF
Thailand ePayment infographic 2012 by Paysbuy.com
PAYSBUY Co.,Ltd.
 
PPTX
SeaJUG May 2012 mybatis
Will Iverson
 
PPT
WebSphere 6.1 Admin Course 1
odedns
 
PPT
Jee course web services
odedns
 
PPTX
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
Altoros
 
PPTX
Secure RESTful API Automation With JavaScript
Jonathan LeBlanc
 
PPTX
Design Summit - RESTful API Overview - John Hardy
ManageIQ
 
PDF
OpenERP 6.1 Framework Changes
Odoo
 
PPTX
Significance of metrics
David Karlsen
 
PDF
Светлана Исакова «Язык Kotlin»
e-Legion
 
PDF
MyBatis 개요와 Java+MyBatis+MySQL 예제
정완 전
 
PPTX
RESTful API Automation with JavaScript
Jonathan LeBlanc
 
PPTX
SpringBoot with MyBatis, Flyway, QueryDSL
Sunghyouk Bae
 
PPTX
MyBatis
Roman Dovgan
 
PDF
Kotlin in action
Ciro Rizzo
 
PDF
A brief introduction to Realm with Kotlin
Leonardo YongUk Kim
 
PPTX
Frisby: Rest API Automation Framework
Quovantis
 
PDF
Developing, Testing and Scaling with Apache Camel - UberConf 2015
Matt Raible
 
Top 50 java ee 7 best practices [con5669]
Ryan Cuprak
 
50 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
Ryan Cuprak
 
Thailand ePayment infographic 2012 by Paysbuy.com
PAYSBUY Co.,Ltd.
 
SeaJUG May 2012 mybatis
Will Iverson
 
WebSphere 6.1 Admin Course 1
odedns
 
Jee course web services
odedns
 
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
Altoros
 
Secure RESTful API Automation With JavaScript
Jonathan LeBlanc
 
Design Summit - RESTful API Overview - John Hardy
ManageIQ
 
OpenERP 6.1 Framework Changes
Odoo
 
Significance of metrics
David Karlsen
 
Светлана Исакова «Язык Kotlin»
e-Legion
 
MyBatis 개요와 Java+MyBatis+MySQL 예제
정완 전
 
RESTful API Automation with JavaScript
Jonathan LeBlanc
 
SpringBoot with MyBatis, Flyway, QueryDSL
Sunghyouk Bae
 
MyBatis
Roman Dovgan
 
Kotlin in action
Ciro Rizzo
 
A brief introduction to Realm with Kotlin
Leonardo YongUk Kim
 
Frisby: Rest API Automation Framework
Quovantis
 
Developing, Testing and Scaling with Apache Camel - UberConf 2015
Matt Raible
 

Similar to Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, MyBatis, and pureQuery (20)

PDF
Fosdem 2011 - A Common Graph Database Access Layer for .Net and Mono
Achim Friedland
 
PDF
Rc173 010d-json 2
Yongfa Huang
 
PDF
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
Dataconomy Media
 
PDF
Practical Models in Practice
CHOOSE
 
PPT
Web development basics (Part-3)
Rajat Pratap Singh
 
PDF
Json demo
Sreeni I
 
PDF
Elixir + Neo4j
Regina Imhoff
 
PDF
Swift Micro-services and AWS Technologies
SimonPilkington8
 
PPTX
Building RESTful Java Applications with EMF
Kenn Hussey
 
PDF
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Databricks
 
PPTX
js.pptx
SuhaibKhan62
 
KEY
Xbase - Implementing Domain-Specific Languages for Java
meysholdt
 
PDF
Querying data on the Web – client or server?
Ruben Verborgh
 
PPTX
Note for Java Programming////////////////
MeghaKulkarni27
 
PDF
Naver_alternative_to_jpa
NAVER Engineering
 
PPT
json.ppt download for free for college project
AmitSharma397241
 
PPTX
Java ce241
Minal Maniar
 
PDF
Angular Weekend
Troy Miles
 
PDF
1st UIM-GDB - Connections to the Real World
Achim Friedland
 
Fosdem 2011 - A Common Graph Database Access Layer for .Net and Mono
Achim Friedland
 
Rc173 010d-json 2
Yongfa Huang
 
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
Dataconomy Media
 
Practical Models in Practice
CHOOSE
 
Web development basics (Part-3)
Rajat Pratap Singh
 
Json demo
Sreeni I
 
Elixir + Neo4j
Regina Imhoff
 
Swift Micro-services and AWS Technologies
SimonPilkington8
 
Building RESTful Java Applications with EMF
Kenn Hussey
 
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Databricks
 
js.pptx
SuhaibKhan62
 
Xbase - Implementing Domain-Specific Languages for Java
meysholdt
 
Querying data on the Web – client or server?
Ruben Verborgh
 
Note for Java Programming////////////////
MeghaKulkarni27
 
Naver_alternative_to_jpa
NAVER Engineering
 
json.ppt download for free for college project
AmitSharma397241
 
Java ce241
Minal Maniar
 
Angular Weekend
Troy Miles
 
1st UIM-GDB - Connections to the Real World
Achim Friedland
 
Ad

More from Vladimir Bacvanski, PhD (7)

PDF
High performance database applications with pure query and ibm data studio.ba...
Vladimir Bacvanski, PhD
 
PDF
Win Friends and Influence People... with DSLs
Vladimir Bacvanski, PhD
 
PDF
How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...
Vladimir Bacvanski, PhD
 
PDF
UML for Data Architects
Vladimir Bacvanski, PhD
 
PPTX
Best Practices of Data Modeling with InfoSphere Data Architect
Vladimir Bacvanski, PhD
 
PPTX
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Vladimir Bacvanski, PhD
 
PPTX
Web 2.0 Development with IBM DB2
Vladimir Bacvanski, PhD
 
High performance database applications with pure query and ibm data studio.ba...
Vladimir Bacvanski, PhD
 
Win Friends and Influence People... with DSLs
Vladimir Bacvanski, PhD
 
How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...
Vladimir Bacvanski, PhD
 
UML for Data Architects
Vladimir Bacvanski, PhD
 
Best Practices of Data Modeling with InfoSphere Data Architect
Vladimir Bacvanski, PhD
 
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Vladimir Bacvanski, PhD
 
Web 2.0 Development with IBM DB2
Vladimir Bacvanski, PhD
 
Ad

Recently uploaded (20)

PDF
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
ScyllaDB
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
PDF
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PPTX
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
PDF
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PDF
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
PPTX
reInforce 2025 Lightning Talk - Scott Francis.pptx
ScottFrancis51
 
PDF
Open Source Milvus Vector Database v 2.6
Zilliz
 
PDF
The Growing Value and Application of FME & GenAI
Safe Software
 
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
ScyllaDB
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
LLM Search Readiness Audit - Dentsu x SEO Square - June 2025.pdf
Nick Samuel
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
reInforce 2025 Lightning Talk - Scott Francis.pptx
ScottFrancis51
 
Open Source Milvus Vector Database v 2.6
Zilliz
 
The Growing Value and Application of FME & GenAI
Safe Software
 

Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, MyBatis, and pureQuery

  • 1. Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, MyBatis, and pureQuery Dr. Vladimir Bacvanski Session Code: E13 May 6, 2011 * 8:00 – 9:00am | Platform: Cross Platform
  • 2. Outline • Database/Programming Languages Chasm • Persistence Options P i t O ti • JDBC • Object R l ti Obj t Relational M l Mapping i • JPA & Hibernate • MyBatis • pureQuery • Conclusions 2
  • 3. Database/Programming Languages Chasm g g g g • Relational Database • Java Customer c1: Customer id  name p phone  email name="Joe" 1      Joe        123‐…       joe@... phone=123‐ 456‐7890 phone=123 456 7890 email="[email protected]" Address Add custId street city y a1: Address 1               1 Nice …             street="1 Nice Way" San… San city="San Francisco" • The world consists of • The world consists of tables objects, which are instances of classes 3
  • 4. Accessing Databases: Many Choices! g y pureQuery JDBC SQLJ MyBatis (iBatis) ) Hibernat e JPA EJB There are more choices, but we'll discuss just the more popular ones 4
  • 5. JDBC • JDBC (Java Database Connectivity) provides an API allowing for explicit creation of SQL queries from Java • The API allows for issuing of SQL commands • Prepared queries • Ad-hoc queries • Callable statements • The result comes back as a cursored table 5
  • 6. Code Example: JDBC p java.sql.PreparedStatement ps =  Table Column Type con.prepareStatement( EMP NAME CHAR(64) "SELECT NAME, ADDRESS, EMP ADDRESS CHAR(128) PHONE_NUM FROM EMP  EMP PHONE_NUM CHAR(10) WHERE NAME=?"); ps.setString(1, name); java.sql.ResultSet rs = ps.executeQuery(); rs.next(); (); Employee myEmp = new Employee(); myEmp.setName(rs.getString(1)); class Employee { myEmp.setHomeAddress(rs.getString(2)); myEmp setHomeAddress(rs getString(2)); public String name; public String name; public String homeAddress; myEmp.setHomePhone(rs.getString(3)); public String homePhone; rs.close(); … } 6
  • 7. Issues with Plain JDBC • Benefits • Performance • It is possible to write optimized queries for a particular task • It is possible to take advantage of underlying DB capabilities • Ease of debugging • The connection between the DB and application code is clear • Drawbacks • Cumbersome programming • The mapping from the application world (Java objects) to the DB world may be cumbersome and complex • Much code may have to be written and debugged • It is easy to introduce mechanical bugs • E.g., closing of connections • JDBC API lags behind modern database features 7
  • 8. Object-Relational Mapping j pp g • Issues with JDBC led to development of O/R mapping, most notably Hibernate as the leading implementation • One popular approach to connect applications to the database is the use of an object-relational mapping tool (ORM) • Many ORM technologies and implementations available: • JPA: The dominant specification • Hibernate, OpenJPA, EclipseLink: JPA implementations 8
  • 9. Mapping Between the Worlds pp g <<enumeration>> BikeType RACING MOUNTAIN STREET UNICYCLE Vehicle vehiclePark owner Person name: String name: String * 1 MotorizedVehicleType * * name: String availableCars legalUsers description: String 1 type * instances MotorizedVehicle Bike fuelCapacity: Integer bikeType: BikeType Address * street: String city: String state: String country: String MOTORIZED_VEHICLE_TYPE VEHICLE_2_PERSON_MAP PERSON_TBL PK id char(10) PK,FK2 legal_driver_id char (10) PK id char (10) PK,FK1 available _car_id char (10) name varchar (50) name varchar (50) description varchar(255) VEHICLE_TBL PK id char(10) FK1 owner_id char(10) name varchar (50) type smallint ADDRESS_TBL PK id varchar (16) MOTORIZED_VEHICLE_TBL BIKE_TBL FK1 occupant _id char(10) PK,FK1,FK2 id char(10) PK,FK1 id char(10) street varchar (250) city varchar (50) fuel_consumption real bike_type smallint state varchar (50) type_id char(10) country varchar (40) 9
  • 10. JPA Example: Annotations p @Entity public class Employee { @Id private Long id; @ManyToOne private Department department; ... } @Entity @ i public class Department { @OneToMany(mappedBy="department") private Collection<Employee> employees = new HashSet(); 10
  • 11. JPA Inheritance Example p @Entity @ @Inheritance @DiscriminatorColumn( name="DISC", discriminatorType=STRING,length=20) @DiscriminatorValue( PERSON ) @DiscriminatorValue(“PERSON") public class Person { ... } @Entity @DiscriminatorValue("CUSTOMER") p public class Customer extends Person { ... } { } 11
  • 12. Hibernate: More than JPA • JPA was heavily inspired by Hibernate • T d Today, Hib Hibernate i l t implements th JPA standard t the t d d • Provides more features in areas: • Primary k generators Pi key t • Control over cascade behaviors • Criteria for query building • Query language HQL • Caching • … 12
  • 13. Issues with ORM Tools • Benefits • Ease of use for the application programmer • The programmer writes code assuming an object model • The tool maps the object model to SQL • Continuity • The domain model (from analysis) is preserved in implementation • Drawbacks • Performance • It is hard for the general p p g purpose mapping tool to take advantage of pp g g the underlying database capabilities • Complex to debug • The mapping can make finding errors very hard 13
  • 14. MyBatis (iBatis) y ( ) • MyBatis was earlier known as iBatis • SQL is fully exposed: MyBatis is not a full ORM! y p y • Persistence access is explicit through SQL • Reduced Java boilerplate code in comparison with JDBC Mapping XML or Annotations Input Output Hashtable Hashtable Mapped  Mapped POJO Statement POJO Primitive Primitive 14
  • 15. SQL Mapping and Call in MyBatis Q pp g y Mapping: <?xml version 1.0 encoding="UTF‐8" ?> <?xml version="1.0" encoding UTF 8  ?> <!DOCTYPE mapper PUBLIC "‐//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis‐3‐mapper.dtd"> <mapper namespace="com.scispike.CustomerMapper"> namespace com.scispike.CustomerMapper > <select id="selectCustomer" parameterType="int" resultType="Customer"> select  from Customer where id = #{id} select * from Customer where id = #{id} </select> </mapper> Call: Customer cust = (Customer) session.selectOne( "com.scispike.CustomerMapper.selectCustomer", 1001); 15
  • 16. Issues with MyBatis y • Benefits • Full control over SQL and improved productivity in comparison with JDBC • Suitable for dealing with legacy databases • Troubleshooting easier in comparison with JPA • D Drawbacks b k • Tooling support is lacking • Productivity initially reduced in comparison with JPA but catches JPA, up later through easier troubleshooting 16
  • 17. p pureQuery Q y • A high-performance, data access platform to simplify developing, managing, securing, developing managing securing and optimizing data access pureQuery Components: • Simple and intuitive API • Enables SQL access to databases or in-memory Java objects y j • Facilitates best practices • Optim Development Studio (integrates with RAD/RSA) • Integrated development environment with Java and SQL support • Improve problem isolation and impact analysis • Optimize existing code: JDBC/JPA/Hibernate/MyBatis • Optim pureQuery Runtime • Flexible static SQL deployment for DB2 17
  • 18. Code Example: pureQuery p p Q y • "Inline" query: Employee myEmp = db.queryFirst( "SELECT NAME, ADDRESS, PHONE_NUM FROM EMP WHERE NAME=?", Employee.class, name); ?" l l ) • Even simpler, if we have a method getEmployee with a simpler Java annotation or XML file with SQL for the query: Employee myEmp = db.getEmployee(name); 18
  • 19. Optim Development Studio: pureQuery IDE p p p Q y Visualize application SQL Replace SQL R l Visualize execution without changing metrics the application Position i P iti in Database Explorer Execute, tune, share, trace, explore 19 SQL
  • 20. SQL Integration with Java Q g • SQL content assist • SQL validation lid ti 20
  • 21. Data Access Objects – pureQuery support j p Q y pp Quickly create JEE Data Access Objects • A i t f An interface with only your methods ith l th d • Methods for each database access • E h method h only your parameters Each th d has l t • SQL can be in XML file or annotations • Implementation automatically generated with best practice database access and optimizations. • T Template-based generation with t l t b d ti ith template customization l t t i ti • Mix hand-written and generated code. • C modify generated code and safely regenerate. Can dif t d d d f l t 21
  • 22. p pureQuery: Optimal Productivity and Control Q y p y Full SQL Control Object-Relational Mapping Managed Objects Code all your SQL JDBC / SQLJ MyBatis Add basic OR mapping and annotated-method style pureQuery Complex O/R mapping and persistence management, but loss of control p pp g p g JPA/Hibernate Adds container management option EJB 3 22
  • 23. Conclusion • Each approach has its strengths and weaknesses • JDBC alone l • To low level for most applications • JPA and Hibernate • Good choice when you own the database, performance not critical • MyBatis • Full control over SQL, reduced boilerplate • pureQuery • Full control over SQL , mixing productivity, static SQL, and integrated tooling 23
  • 24. Getting in Touch g • Email: [email protected] • Blog: htt // Bl http://www.OnBuildingSoftware.com/ O B ildi S ft / • Twitter: http://twitter.com/OnSoftware • LinkedIn: http://www.linkedin.com/in/VladimirBacvanski Li k dI htt // li k di /i /Vl di i B ki • Parts of the presentation are from SciSpike courses: • Developing Database Applications with Optim Development Studio and pureQuery • Hibernate 24