SlideShare una empresa de Scribd logo
1 de 24
Descargar para leer sin conexión
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

Más contenido relacionado

Destacado

Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Ryan Cuprak
 
50 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
50 EJB 3 Best Practices in 50 Minutes - JavaOne 201450 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
50 EJB 3 Best Practices in 50 Minutes - JavaOne 2014Ryan Cuprak
 
Thailand ePayment infographic 2012 by Paysbuy.com
Thailand ePayment infographic 2012 by Paysbuy.comThailand ePayment infographic 2012 by Paysbuy.com
Thailand ePayment infographic 2012 by Paysbuy.comPAYSBUY Co.,Ltd.
 
SeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisSeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisWill Iverson
 
WebSphere 6.1 Admin Course 1
WebSphere 6.1 Admin Course 1WebSphere 6.1 Admin Course 1
WebSphere 6.1 Admin Course 1odedns
 
Jee course web services
Jee course web servicesJee course web services
Jee course web servicesodedns
 
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...Altoros
 
Secure RESTful API Automation With JavaScript
Secure RESTful API Automation With JavaScriptSecure RESTful API Automation With JavaScript
Secure RESTful API Automation With JavaScriptJonathan LeBlanc
 
Design Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyDesign Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyManageIQ
 
OpenERP 6.1 Framework Changes
OpenERP 6.1 Framework ChangesOpenERP 6.1 Framework Changes
OpenERP 6.1 Framework ChangesOdoo
 
Significance of metrics
Significance of metricsSignificance of metrics
Significance of metricsDavid Karlsen
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»e-Legion
 
MyBatis 개요와 Java+MyBatis+MySQL 예제
MyBatis 개요와 Java+MyBatis+MySQL 예제MyBatis 개요와 Java+MyBatis+MySQL 예제
MyBatis 개요와 Java+MyBatis+MySQL 예제정완 전
 
RESTful API Automation with JavaScript
RESTful API Automation with JavaScriptRESTful API Automation with JavaScript
RESTful API Automation with JavaScriptJonathan LeBlanc
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSunghyouk Bae
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
A brief introduction to Realm with Kotlin
A brief introduction to Realm with KotlinA brief introduction to Realm with Kotlin
A brief introduction to Realm with KotlinLeonardo YongUk Kim
 
Frisby: Rest API Automation Framework
Frisby: Rest API Automation FrameworkFrisby: Rest API Automation Framework
Frisby: Rest API Automation FrameworkQuovantis
 
Developing, Testing and Scaling with Apache Camel - UberConf 2015
Developing, Testing and Scaling with Apache Camel - UberConf 2015Developing, Testing and Scaling with Apache Camel - UberConf 2015
Developing, Testing and Scaling with Apache Camel - UberConf 2015Matt Raible
 

Destacado (20)

Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]
 
50 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
50 EJB 3 Best Practices in 50 Minutes - JavaOne 201450 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
50 EJB 3 Best Practices in 50 Minutes - JavaOne 2014
 
Thailand ePayment infographic 2012 by Paysbuy.com
Thailand ePayment infographic 2012 by Paysbuy.comThailand ePayment infographic 2012 by Paysbuy.com
Thailand ePayment infographic 2012 by Paysbuy.com
 
SeaJUG May 2012 mybatis
SeaJUG May 2012 mybatisSeaJUG May 2012 mybatis
SeaJUG May 2012 mybatis
 
WebSphere 6.1 Admin Course 1
WebSphere 6.1 Admin Course 1WebSphere 6.1 Admin Course 1
WebSphere 6.1 Admin Course 1
 
Jee course web services
Jee course web servicesJee course web services
Jee course web services
 
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
How to Choose an API Automation Tool for a Distributed Cloud-based App: To...
 
Secure RESTful API Automation With JavaScript
Secure RESTful API Automation With JavaScriptSecure RESTful API Automation With JavaScript
Secure RESTful API Automation With JavaScript
 
Design Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John HardyDesign Summit - RESTful API Overview - John Hardy
Design Summit - RESTful API Overview - John Hardy
 
OpenERP 6.1 Framework Changes
OpenERP 6.1 Framework ChangesOpenERP 6.1 Framework Changes
OpenERP 6.1 Framework Changes
 
Significance of metrics
Significance of metricsSignificance of metrics
Significance of metrics
 
Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»Светлана Исакова «Язык Kotlin»
Светлана Исакова «Язык Kotlin»
 
MyBatis 개요와 Java+MyBatis+MySQL 예제
MyBatis 개요와 Java+MyBatis+MySQL 예제MyBatis 개요와 Java+MyBatis+MySQL 예제
MyBatis 개요와 Java+MyBatis+MySQL 예제
 
RESTful API Automation with JavaScript
RESTful API Automation with JavaScriptRESTful API Automation with JavaScript
RESTful API Automation with JavaScript
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
 
MyBatis
MyBatisMyBatis
MyBatis
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
A brief introduction to Realm with Kotlin
A brief introduction to Realm with KotlinA brief introduction to Realm with Kotlin
A brief introduction to Realm with Kotlin
 
Frisby: Rest API Automation Framework
Frisby: Rest API Automation FrameworkFrisby: Rest API Automation Framework
Frisby: Rest API Automation Framework
 
Developing, Testing and Scaling with Apache Camel - UberConf 2015
Developing, Testing and Scaling with Apache Camel - UberConf 2015Developing, Testing and Scaling with Apache Camel - UberConf 2015
Developing, Testing and Scaling with Apache Camel - UberConf 2015
 

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

Fosdem 2011 - A Common Graph Database Access Layer for .Net and Mono
Fosdem 2011 - A Common Graph Database Access Layer for .Net and MonoFosdem 2011 - A Common Graph Database Access Layer for .Net and Mono
Fosdem 2011 - A Common Graph Database Access Layer for .Net and MonoAchim Friedland
 
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft..."Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...Dataconomy Media
 
Practical Models in Practice
Practical Models in PracticePractical Models in Practice
Practical Models in PracticeCHOOSE
 
Web development basics (Part-3)
Web development basics (Part-3)Web development basics (Part-3)
Web development basics (Part-3)Rajat Pratap Singh
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSimonPilkington8
 
Building RESTful Java Applications with EMF
Building RESTful Java Applications with EMFBuilding RESTful Java Applications with EMF
Building RESTful Java Applications with EMFKenn Hussey
 
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...Databricks
 
Xbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for JavaXbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for Javameysholdt
 
Querying data on the Web – client or server?
Querying data on the Web – client or server?Querying data on the Web – client or server?
Querying data on the Web – client or server?Ruben Verborgh
 
Note for Java Programming////////////////
Note for Java Programming////////////////Note for Java Programming////////////////
Note for Java Programming////////////////MeghaKulkarni27
 
Angular Weekend
Angular WeekendAngular Weekend
Angular WeekendTroy Miles
 
1st UIM-GDB - Connections to the Real World
1st UIM-GDB - Connections to the Real World1st UIM-GDB - Connections to the Real World
1st UIM-GDB - Connections to the Real WorldAchim Friedland
 
HBaseCon 2015: S2Graph - A Large-scale Graph Database with HBase
HBaseCon 2015: S2Graph - A Large-scale Graph Database with HBaseHBaseCon 2015: S2Graph - A Large-scale Graph Database with HBase
HBaseCon 2015: S2Graph - A Large-scale Graph Database with HBaseHBaseCon
 

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

Fosdem 2011 - A Common Graph Database Access Layer for .Net and Mono
Fosdem 2011 - A Common Graph Database Access Layer for .Net and MonoFosdem 2011 - A Common Graph Database Access Layer for .Net and Mono
Fosdem 2011 - A Common Graph Database Access Layer for .Net and Mono
 
Rc173 010d-json 2
Rc173 010d-json 2Rc173 010d-json 2
Rc173 010d-json 2
 
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft..."Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
"Source Code Abstracts Classification Using CNN", Vadim Markovtsev, Lead Soft...
 
Practical Models in Practice
Practical Models in PracticePractical Models in Practice
Practical Models in Practice
 
Web development basics (Part-3)
Web development basics (Part-3)Web development basics (Part-3)
Web development basics (Part-3)
 
Json demo
Json demoJson demo
Json demo
 
Elixir + Neo4j
Elixir + Neo4jElixir + Neo4j
Elixir + Neo4j
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS Technologies
 
Building RESTful Java Applications with EMF
Building RESTful Java Applications with EMFBuilding RESTful Java Applications with EMF
Building RESTful Java Applications with EMF
 
Neo4j
Neo4jNeo4j
Neo4j
 
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
Neo4j Morpheus: Interweaving Table and Graph Data with SQL and Cypher in Apac...
 
js.pptx
js.pptxjs.pptx
js.pptx
 
Xbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for JavaXbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for Java
 
Querying data on the Web – client or server?
Querying data on the Web – client or server?Querying data on the Web – client or server?
Querying data on the Web – client or server?
 
Note for Java Programming////////////////
Note for Java Programming////////////////Note for Java Programming////////////////
Note for Java Programming////////////////
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
 
Java ce241
Java ce241Java ce241
Java ce241
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
1st UIM-GDB - Connections to the Real World
1st UIM-GDB - Connections to the Real World1st UIM-GDB - Connections to the Real World
1st UIM-GDB - Connections to the Real World
 
HBaseCon 2015: S2Graph - A Large-scale Graph Database with HBase
HBaseCon 2015: S2Graph - A Large-scale Graph Database with HBaseHBaseCon 2015: S2Graph - A Large-scale Graph Database with HBase
HBaseCon 2015: S2Graph - A Large-scale Graph Database with HBase
 

Más de Vladimir Bacvanski, PhD

High performance database applications with pure query and ibm data studio.ba...
High performance database applications with pure query and ibm data studio.ba...High performance database applications with pure query and ibm data studio.ba...
High performance database applications with pure query and ibm data studio.ba...Vladimir Bacvanski, PhD
 
Win Friends and Influence People... with DSLs
Win Friends and Influence People... with DSLsWin Friends and Influence People... with DSLs
Win Friends and Influence People... with DSLsVladimir Bacvanski, PhD
 
How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...
How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...
How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...Vladimir Bacvanski, PhD
 
Best Practices of Data Modeling with InfoSphere Data Architect
Best Practices of Data Modeling with InfoSphere Data ArchitectBest Practices of Data Modeling with InfoSphere Data Architect
Best Practices of Data Modeling with InfoSphere Data ArchitectVladimir Bacvanski, PhD
 
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Vladimir Bacvanski, PhD
 

Más de Vladimir Bacvanski, PhD (7)

High performance database applications with pure query and ibm data studio.ba...
High performance database applications with pure query and ibm data studio.ba...High performance database applications with pure query and ibm data studio.ba...
High performance database applications with pure query and ibm data studio.ba...
 
Win Friends and Influence People... with DSLs
Win Friends and Influence People... with DSLsWin Friends and Influence People... with DSLs
Win Friends and Influence People... with DSLs
 
How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...
How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...
How to Crunch Petabytes with Hadoop and Big Data using InfoSphere BigInsights...
 
UML for Data Architects
UML for Data ArchitectsUML for Data Architects
UML for Data Architects
 
Best Practices of Data Modeling with InfoSphere Data Architect
Best Practices of Data Modeling with InfoSphere Data ArchitectBest Practices of Data Modeling with InfoSphere Data Architect
Best Practices of Data Modeling with InfoSphere Data Architect
 
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
 
Web 2.0 Development with IBM DB2
Web 2.0 Development with IBM DB2Web 2.0 Development with IBM DB2
Web 2.0 Development with IBM DB2
 

Último

UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 

Último (20)

UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 

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="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
  • 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: 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