crash introduction to modern java data access: understanding jpa, hibernate, mybatis, and purequery

Post on 20-Dec-2014

2.019 Views

Category:

Technology

5 Downloads

Preview:

Click to see full reader

DESCRIPTION

 

TRANSCRIPT

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

Dr. Vladimir Bacvanski

Session Code: E13Session Code: E13May 6, 2011 * 8:00 May 6, 2011 * 8:00 –– 9:00am | Platform: Cross Platform9:00am | Platform: Cross Platform

Outline

• Database/Programming Languages ChasmP i t O ti• Persistence Options

• JDBCObj t R l ti l M i• Object Relational Mapping

• JPA & Hibernate• MyBatis• pureQuery• Conclusions

2

Database/Programming Languages Chasmg g g g

• Relational Database • JavaCustomer

pid  name phone  email1      Joe        123‐…      

c1: Customername="Joe"phone=123 456 7890joe@...

Add

email="joe@xyz.com"phone=123‐ 456‐7890email="joe@xyz.com"

AddressycustId street city

1               1 Nice …            San

a1: Addressstreet="1 Nice Way"

• The world consists of • The world consists of

San…city="San Francisco"

tables objects, which are instances of classes 3

Accessing Databases: Many Choices!g yJDBCpureQuery

SQLJSQLJMyBatisMyBatis(iBatis)

Hibernate

Hibernate

)(iBatis)

JPA EJB

There are more choices, but we'll discuss just the more popular ones4

JDBC

• JDBC (Java Database Connectivity) provides an API allowing for explicit creation of SQL queries from Javaallowing for explicit creation of SQL queries from Java

• The API allows for issuing of SQL commands• Prepared queries• Prepared queries• Ad-hoc queries• Callable statements

• The result comes back as a cursored table

5

Code Example: JDBCpTable Column TypeEMP NAME CHAR(64)

java.sql.PreparedStatement ps = con.prepareStatement(

EMP ADDRESS CHAR(128)

EMP PHONE_NUM CHAR(10)

"SELECT NAME, ADDRESS,PHONE_NUM FROM EMP WHERE NAME=?");

ps.setString(1, name);java.sql.ResultSet rs = ps.executeQuery();rs.next();

class Employee {public String name;

();Employee myEmp = new Employee();myEmp.setName(rs.getString(1));myEmp setHomeAddress(rs getString(2)); public String name;

public String homeAddress;public String homePhone;…

myEmp.setHomeAddress(rs.getString(2));myEmp.setHomePhone(rs.getString(3));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• 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 complexworld 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 Mappingj pp g

• Issues with JDBC led to development of O/R mapping, most notably Hibernate as the leading implementationmost notably Hibernate as the leading implementation

• One popular approach to connect applications to the database is the use of an object-relational mapping tooldatabase is the use of an object-relational mapping tool (ORM)

• Many ORM technologies and implementations available:Many ORM technologies and implementations available:• JPA: The dominant specification• Hibernate, OpenJPA, EclipseLink: JPA implementations

8

Mapping Between the Worldspp g

RACINGMOUNTAIN

<<enumeration>>BikeType

name: String

Vehicle

name: String

Person

1*

vehiclePark owner

**

availableCars legalUsers

STREETUNICYCLE

name: Stringdescription: String

MotorizedVehicleType

fuelCapacity: Integer

MotorizedVehicle

bikeType: BikeType

Bikeinstances

type1

*street: Stringcity: Stringstate: Stringcountry: String

Address

*

VEHICLE_2_PERSON_MAP

PK,FK2 legal_driver_id char (10)PK,FK1 available _car_id char (10)

PERSON_TBL

PK id char (10)

name varchar (50)

MOTORIZED_VEHICLE_TYPE

PK id char(10)

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

PK,FK1,FK2 id char(10)

fuel_consumption realtype_id char(10)

BIKE_TBL

PK,FK1 id char(10)

bike_type smallint

PK id varchar (16)

FK1 occupant_id char(10)street varchar (250)city varchar (50)state varchar (50)country varchar (40)

9

JPA Example: Annotationsp@Entitypublic class Employee {

@Idprivate Long id;

@ManyToOneprivate Department department;...

}

@ i@Entitypublic class Department {

@OneToMany(mappedBy="department") private Collection<Employee> employees = new HashSet();

10

JPA Inheritance Examplep@Entity

@Inheritance@

@DiscriminatorColumn(name="DISC", discriminatorType=STRING,length=20)

@DiscriminatorValue(“PERSON")@DiscriminatorValue( PERSON )

public class Person { ... }

@Entity

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

11

Hibernate: More than JPA

• JPA was heavily inspired by HibernateT d Hib t i l t th JPA t d d• Today, Hibernate implements the JPA standard

• Provides more features in areas:P i k t• Primary key generators

• Control over cascade behaviors• Criteria for query buildingCriteria for query building• Query language HQL• Caching• …

12

Issues with ORM Tools• Benefits

• Ease of use for the application programmer• 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• Drawbacks• Performance

• It is hard for the general purpose mapping tool to take advantage of g p p pp g gthe underlying database capabilities

• Complex to debug• The mapping can make finding errors very hard• 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

MappingXML or Annotations

Input

Hashtable

Output

HashtableMapped

POJO POJO

Mapped Statement

Primitive Primitive

14

SQL Mapping and Call in MyBatisQ pp g yMapping:<?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"><mapper 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 MyBatisy• Benefits

• Full control over SQL and improved productivity in comparison• Full control over SQL and improved productivity in comparison with JDBC

• Suitable for dealing with legacy databases• Troubleshooting easier in comparison with JPA

D b k• Drawbacks• Tooling support is lacking• Productivity initially reduced in comparison with JPA but catches• Productivity initially reduced in comparison with JPA, but catches

up later through easier troubleshooting

16

pureQueryp Q y

• A high-performance, data access platform to simplify developing managing securing and optimizing datadeveloping, managing, securing, and optimizing data access

pureQuery Components:• Simple and intuitive API

• Enables SQL access to databases or in-memory Java objectsy j• Facilitates best practices

• Optim Development Studio (integrates with RAD/RSA)• Integrated development environment with Java and SQL supportIntegrated development environment with Java and SQL support • Improve problem isolation and impact analysis• Optimize existing code: JDBC/JPA/Hibernate/MyBatis

• Optim pureQuery Runtime• Optim pureQuery Runtime• Flexible static SQL deployment for DB2

17

Code Example: pureQueryp p Q y

• "Inline" query:

Employee myEmp = db.queryFirst("SELECT NAME, ADDRESS, PHONE_NUM FROM EMP

?" l l )WHERE NAME=?", Employee.class, name);

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

Employee myEmp = db.getEmployee(name);

18

Optim Development Studio: pureQuery IDEp p p Q y

R l SQL

Visualize application SQL

Visualize execution metrics

Replace SQL without changing

the application

P iti i

Execute, tune, share, trace, explore

SQL

Position in Database Explorer

19

SQL Integration with JavaQ g• SQL content assist

SQL lid ti• SQL validation

20

Data Access Objects – pureQuery supportj p Q y pp

Quickly create JEE Data Access ObjectsA i t f ith l th d• An interface with only your methods

• Methods for each database accessE h th d h l t• Each method has only your parameters

• SQL can be in XML file or annotations• Implementation automatically generated with best practice

database access and optimizations.T l t b d ti ith t l t t i ti• Template-based generation with template customization

• Mix hand-written and generated code. C dif t d d d f l t• Can modify generated code and safely regenerate.

21

pureQuery: Optimal Productivity and Controlp Q y p y

Managed Objects Object-Relational MappingFull SQL Control

Code all your SQL

JDBC / SQLJJDBC / SQLJ

MyBatis

Complex O/R mapping and persistence management, but loss of control

Add basic OR mapping and annotated-method stylepureQuery

p pp g p g

Adds container management option

JPA/Hibernate

EJB 3

22

Conclusion

• Each approach has its strengths and weaknessesJDBC l• JDBC alone• To low level for most applications

• JPA and Hibernate• JPA and Hibernate• Good choice when you own the database, performance not critical

• MyBatis• MyBatis• Full control over SQL, reduced boilerplate

• pureQuerypureQuery• Full control over SQL , mixing productivity, static SQL, and

integrated tooling

23

Getting in Touchg

• Email: vladimir.bacvanski@scispike.comBl htt // O B ildi S ft /• Blog: http://www.OnBuildingSoftware.com/

• Twitter: http://twitter.com/OnSoftwareLi k dI htt // li k di /i /Vl di i B ki• LinkedIn: http://www.linkedin.com/in/VladimirBacvanski

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

24

top related