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

Dr. Vladimir Bacvanski

Session Code: E13 May 6, 2011 * 8:00 – 9:00am | Platform: Cross Platform Outline

/Programming Languages Chasm • Persistence Options • JDBC • Object Relational Mapping • JPA & Hibernate • MyBatis • pureQuery • Conclusions

2 Database/Programming Languages Chasm • Relational Database • Java

Customer c1: Customer id name phone email name="Joe" 1 Joe 123-… joe@... phone=123- 456-7890 email="[email protected]"

Address custId street city a1: Address 1 1 Nice … street="1 Nice Way" San… city="San Francisco" • The world consists of • The world consists of tables objects, which are instances of classes 3 Accessing : Many Choices!

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 java..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)); public String name; myEmp.setHomePhone(rs.getString(3)); public String homeAddress; 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

• 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 O/R Mapping The Object-Oriented View

<> BikeType

RACING MOUNTAIN STREET UNICYCLE Vehicle vehiclePark owner Person name: String name: String Mapping: * 1

Annotations or XML MotorizedVehicleType * * name: String availableCars legalUsers description: String

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

map The Relational Database View

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) map name varchar(50) name varchar(50) description varchar(255)

map VEHICLE_TBL

PK id char(10)

FK1 owner_id char(10) name varchar(50) map 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

@Entity public class Employee { @Id private Long id;

@ManyToOne private Department department; ... }

@Entity public class Department { @OneToMany(mappedBy="department")‏ private Collection 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

Mapping XML or Annotations Input Output

Hashtable Hashtable Mapped POJO Statement POJO

Primitive Primitive

14 SQL Mapping and Call in MyBatis

Mapping:

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 DB2 17 Code Example: pureQuery

• "Inline" query:

Employee myEmp = db.queryFirst( "SELECT NAME, ADDRESS, PHONE_NUM FROM EMP WHERE 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 application SQL Replace SQL Visualize without changing execution metrics the application

Position in Database Explorer Execute, tune, share, trace, 19 explore SQL 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

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 JPA/Hibernate

Adds container management option EJB 3

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