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

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

  • 1.
    Crash Introduction to ModernJava 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: ManyChoices! 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 (JavaDatabase 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 PlainJDBC • 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 theWorlds 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 thanJPA • 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 ORMTools • 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 andCall 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 withJava 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: OptimalProductivity 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 approachhas 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