Crash Introduction to Modern Java Data Access
Transcript of Crash Introduction to Modern Java Data Access
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
• JDBC
• Object Relational Mapping
• JPA & Hibernate
• MyBatis
• pureQuery
• Conclusions
2
Database/Programming Languages Chasm
• Relational Database
• The world consists of
tables
• Java
• The world consists of
objects, which are
instances of classes
Customerid name phone email1 Joe 123-… joe@...
AddresscustId street city1 1 Nice … San…
c1: Customername="Joe"
phone=123- 456-7890
email="[email protected]"
a1: Addressstreet="1 Nice Way"
city="San Francisco"
3
Accessing Databases: Many Choices!
JDBCpureQuery
SQLJ
Hibernate
JPA
MyBatis(iBatis)
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 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
Table Column TypeEMP NAME CHAR(64)
EMP ADDRESS CHAR(128)
EMP PHONE_NUM CHAR(10)
class Employee {public String name;public String homeAddress;public String homePhone;…
}
java.sql.PreparedStatement ps = con.prepareStatement(
"SELECT NAME, ADDRESS,PHONE_NUM FROM EMP
WHERE NAME=?");
ps.setString(1, name);
java.sql.ResultSet rs = ps.executeQuery();
rs.next();
Employee myEmp = new Employee();
myEmp.setName(rs.getString(1));
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
• 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
• 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 WorldsThe Object-Oriented View
The Relational Database View
VEHICLE_TBL
PK id char(10)
FK1 owner_id char(10)
name varchar(50)
type smallint
MOTORIZED_VEHICLE_TBL
PK,FK1,FK2 id char(10)
fuel_consumption real
type_id char(10)
BIKE_TBL
PK,FK1 id char(10)
bike_type smallint
VEHICLE_2_PERSON_MAP
PK,FK2 legal_driver_id char(10)
PK,FK1 available_car_id char(10)
ADDRESS_TBL
PK id varchar(16)
FK1 occupant_id char(10)
street varchar(250)
city varchar(50)
state varchar(50)
country varchar(40)
PERSON_TBL
PK id char(10)
name varchar (50)
MOTORIZED_VEHICLE_TYPE
PK id char(10)
name varchar(50)
description varchar(255)
name: String
Vehicle
name: String
Person
1*
vehiclePark owner
**
availableCars legalUsers
fuelCapacity: Integer
MotorizedVehicle
bikeType: BikeType
Bike
RACING
MOUNTAIN
STREET
UNICYCLE
<<enumeration>>
BikeType
name: String
description: String
MotorizedVehicleType
instances
type1
*
street: String
city: String
state: String
country: String
Address
*
O/R Mapping
map
map
map
map
map
Mapping:
Annotations or XML
9
JPA Example: Annotations
@Entity
public class Employee {
@Id
private Long id;
@ManyToOne
private Department department;
...
}
@Entity
public class Department {
@OneToMany(mappedBy="department")
private Collection<Employee> employees = new HashSet();
10
JPA Inheritance Example
@Entity
@Inheritance
@DiscriminatorColumn(name="DISC", discriminatorType=STRING,length=20)
@DiscriminatorValue(“PERSON")
public class Person { ... }
@Entity
@DiscriminatorValue("CUSTOMER")
public class Customer extends Person { ... }
11
Hibernate: More than JPA
• JPA was heavily inspired by Hibernate
• Today, Hibernate implements the JPA standard
• Provides more features in areas:
• Primary key generators
• 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 purpose mapping tool to take advantage of
the underlying database capabilities
• Complex to debug
• The mapping can make finding errors very hard
13
MyBatis (iBatis)
• MyBatis was earlier known as iBatis
• SQL is fully exposed: MyBatis is not a full ORM!
• Persistence access is explicit through SQL
• Reduced Java boilerplate code in comparison with JDBC
Input
Hashtable
POJO
Primitive
MappingXML or Annotations
Output
Hashtable
POJO
Primitive
Mapped Statement
14
SQL Mapping and Call in MyBatis
Mapping:
<?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">
<select id="selectCustomer" parameterType="int"
resultType="Customer">
select * from Customer where id = #{id}
</select>
</mapper>
Call:
Customer cust = (Customer) session.selectOne(
"com.scispike.CustomerMapper.selectCustomer", 1001);
15
Issues with MyBatis
• Benefits
• Full control over SQL and improved productivity in comparison
with JDBC
• Suitable for dealing with legacy databases
• Troubleshooting easier in comparison with JPA
• Drawbacks
• Tooling support is lacking
• Productivity initially reduced in comparison with JPA, but catches
up later through easier troubleshooting
16
pureQuery
• A high-performance, data access platform to simplify
developing, managing, securing, and optimizing data
access
pureQuery Components:• Simple and intuitive API
• Enables SQL access to databases or in-memory Java objects
• 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 DB217
Code Example: pureQuery
• "Inline" query:
Employee myEmp = db.queryFirst("SELECT NAME, ADDRESS, PHONE_NUM FROM EMPWHERE NAME=?", Employee.class, name);
• Even 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 IDE
Visualize
execution metrics
Execute, tune,
share, trace,
explore SQL
Replace SQL
without changing
the application
Position in
Database Explorer
Visualize
application SQL
19
SQL Integration with Java• SQL content assist
• SQL validation
20
Data Access Objects – pureQuery support
Quickly create JEE Data Access Objects
• An interface with only your methods
• Methods for each database access
• Each method has only your parameters
• SQL can be in XML file or annotations
• Implementation automatically generated with best practice
database access and optimizations.
• Template-based generation with template customization
• Mix hand-written and generated code.
• Can modify generated code and safely regenerate.
21
pureQuery: Optimal Productivity and Control
Managed Objects Object-Relational MappingFull SQL Control
Code all your SQL
Complex O/R mapping and persistence management, but loss of control
Adds container management option
JDBC / SQLJ
MyBatis
JPA/Hibernate
EJB 3
Add basic OR mapping and annotated-method stylepureQuery
22
Conclusion
• Each approach has its strengths and weaknesses
• JDBC alone
• 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
• Email: [email protected]
• Blog: http://www.OnBuildingSoftware.com/
• Twitter: http://twitter.com/OnSoftware
• LinkedIn: http://www.linkedin.com/in/VladimirBacvanski
24