migrating a classic hibernate application to use the ... · the java persistence api (jpa) is a...

22
WebSphere Application Server 05/28/10 © 2010 IBM Corporation Migrating a Classic Hibernate Application to Use the WebSphere JPA 2.0 Feature Pack Author: Lisa Walkosz [email protected] Date: May 28, 2010

Upload: trinhtuyen

Post on 15-Feb-2019

238 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

05/28/10 © 2010 IBM Corporation

Migrating a Classic Hibernate Application to Use the WebSphere JPA 2.0 Feature Pack

Author: Lisa [email protected]

Date: May 28, 2010

Page 2: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/102

THE INFORMATION CONTAINED IN THIS REPORT IS PROVIDED FOR INFORMATIONAL PURPOSES ONLY. ALTHOUGH EFFORTS WERE MADE TO VERIFY THE COMPLETENESS AND ACCURACY OF THE INFORMATION CONTAINED IN THIS PRESENTATION, IT IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. IN ADDITION, THIS INFORMATION IS BASED ON IBM’S CURRENT PRODUCT PLANS AND STRATEGY, WHICH ARE SUBJECT TO CHANGE BYIBM WITHOUT NOTICE.

IBM SHALL NOT BE RESPONSIBLE FOR ANY DAMAGES ARISING OUT OF THE USE OF, OR OTHERWISE RELATED TO, THIS REPORT OR ANY OTHER DOCUMENTATION. NOTHING CONTAINED IN THIS REPORT IS INTENDED TO, OR SHALL HAVE THE EFFECT OF CREATING ANY WARRANTY OR REPRESENTATION FROM IBM (OR ITS AFFILIATES OR ITS OR THEIR SUPPLIERS AND/OR LICENSORS); OR ALTERING THE TERMS AND CONDITIONS OF THE APPLICABLE LICENSE AGREEMENT GOVERNING THE USE OF IBM SOFTWARE.

Page 3: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/103

Trademarks and Service Marks

The following terms are trademarks of the IBM Corporation in the United States or other countries or both:

● IBM● WebSphere● WebSphere Application Server

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.

Hibernate is licensed under the LGPL v2.1

Other company, product and service names may be trademarks or service marks of others.

Page 4: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/104

Executive Summary

The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database. JPA makes it easy to program without writing complex SQL queries, continues your object relational model, and has opportunities to make gains in usability and performance.

WebSphere Application Server has the ability to set up and use many persistence providers available to application developers. However, to take advantage of the features, performance, and support, the persistence provider that comes with WebSphere is recommended. Customers who have used the Hibernate implementation of persistence can now convert their applications into the JPA implementation included in WebSphere.

Page 5: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/105

Audience

This report is intended for customers using classic Hibernate (Hibernate 3.0 or earlier) as their persistence provider who wish to switch to JPA because of desired features, support, maintainability, and standardization.

For example, Java EE 6 JPA 2.0 is included in the IBM WebSphere Application Server v7 Feature Pack for OSGi Applications and Java Persistence API (JPA) 2.0.

WebSphere JPA 1.0 is the provider for v6.1 with EJB 3.0 Feature Pack, which is also available in WebSphere Application Server v7.

Page 6: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/106

Scenario Description

This report describes how to migrate an application using Hibernate classic as its persistence provider into the WebSphere implementation of JPA in a WebSphere Application Server environment. Hibernate classic refers to a Hibernate application that uses the Hibernate Session class to perform its persistence. This also usually refers to applications using Hibernate 2.0 or earlier.

As part of the process we will describe a unit test while updating the application and a system test to validate its robustness in a cluster with light stress.

Page 7: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/107

Topology

Since our test involves application changes, we used a WebSphere Application Server base server and the IBM Rational Application Developer 7.5 as our development environment. New functionality of the JPA 2.0 feature pack will require you to use RAD 8.0. After unit test, we used a small clustered environment under light load to determine if any multithreaded issues exist. This cell consisted of 1 cluster with 4 servers on 2 nodes with a proxy server. Versions of WebSphere and feature packs are shown on the migration path chart. Please visit the IBM website to find prerequisites for each feature pack version and the required fix packs to install them.

System test/ stress

Unit test/ application changes

RAD

cluster

server

server

DB2

WAS server

proxy

server

server

Page 8: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/108

Applications

For this test, we used an application originally written in Hibernate classic on WebSphere Application Server 6.1.

Our application uses a complex relational database containing various product deliverables with brands, types, division, and phases. We will take the original Hibernate mappings and convert them using object-relational mappings (ORM) to be used with JPA.

For the front end, we created a simple servlet that has multiple different queries to test. We also created a simple write test that will change the name of a queried product and validate that it has been changed.

Page 9: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/109

Migration PathThis is the migration path we tested. Wherever you are in this path, it is possible to migrate to JPA 2.0. For example, you can skip the part of applying the EJB 3.0 feature pack if you start at WAS 6.1 by just going to WAS 7.0, or skip converting to JPA 1.0 by installing the JPA 2.0 feature pack and going straight to JPA 2.0

Page 10: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1010

Update From Proprietary Hibernate Code Converting a classic Hibernate application to use Websphere’s JPA

is simple. In fact, since JPA is bundled with WebSphere Application Server, it can actually be easier to configure.

Since all applications tend to be different, the WebSphere Application Server Information Center doesn't have specific information on migrating your application. However, there is a developerWorks article that provides a bit of background, reasoning, and some comparison code for developers switching over. During our testing, we always referred to this article: [Migrating legacy Hibernate application to OpenJPA and EJB 3.0].

Page 11: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1011

Session vs EntityManager The Hibernate Session can be compared to JPA's EntityManager which takes

care of the underlying access to a datasource. There are a few differences between the behavior of an entity manager vs. a session and it's good to be aware of what they are.

JPA uses the EntityManager to handle persistence. When switching over from Hibernate, you can change anything that was using the Session API (session) and replace it with the Entity Manager (em). For example, you will use em.createQuery() instead of session.createQuery() for all your queries, as well as for updates, removals, etc.

Another difference is that the Hibernate Session will automatically clean up your persistence unit when done application-managed entity, while the entity manager will have to be closed manually. This gives more control to the programmer as well as a performance gain, but can be easily overlooked and cause a memory issue if not handled.

JPA uses new concepts like persistence contexts, persistence units and entities. It will be a good idea to review these in detail [Managing Entities – The Java EE 5 Tutorial]

If you are using the container-managed entity, the container will automatically clean up your persistence unit for you.

Page 12: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1012

Slightly different query syntax

There are a few programming model differences between HQL (Hibernate's query statements) and JPQL (JPA's query statements) that will require time and effort to change.

For example, the SELECT is not required in HQL and some methods on the query object such as setString() and setParameter() are named differently. While the syntax differences are minor, every query needs to be found and changed.

// Hibernate's HQL queryQuery query = session.createQuery("FROM Deliverable as d LEFT JOIN FETCH d.msiProduct where id =: id");query.setString(id, deliverableId).uniqueResult();deliverables = query.list();

// JPA's JPQL queryQuery query = em.createQuery("SELECT d FROM Deliverable d LEFT JOIN FETCH d.msiProduct where id =: id");query.setParameter(id, deliverableId);deliverables = query.getSingleResult();

You should check both APIs when converting more advanced queries.

Page 13: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1013

Hibernate.cfg.xml to ORM and annotations The hibernate.cfg.xml file is used to describe persistence options and

relational mappings. The mapping resource usually points to another Object.hbm.xml and contains your mappings and relationships.

// hibernate.cfg.xml<mapping resource="com/ibm/clearinghouse/service/model/Deliverable.hbm.xml"/>// Deliverable.hbm.xml<hibernate-mapping><class name="com.ibm.clearinghouse.service.model.Deliverable" table="SHDBA.PRODUCT" batch-size="50" lazy="true"><id name="id" column="PRODUCT_INSTANCE_ID"></id>

<property name="version"/>

For JPA, you can use annotations inside your code or the orm.xml and persistence.xml files to configure your data model mapping and options.

// orm.xml<entity class="com.ibm.clearinghouse.service.model.Deliverable" name="Deliverable"><table name="PRODUCT" schema="SHDBA"/> <attributes> <id name="id"><column name="PRODUCT_INSTANCE_ID"/><generated-value strategy="IDENTITY" /></id>// annotations@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name="PRODUCT_INSTANCE_ID")

Refer to the developerWorks article for a more detailed explanation of converting the data model.

Page 14: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1014

Update code to run on WebSphere v7.0

Like any migration, there may be API changes from one application server version to another. In our test, we migrated from WebSphere Application Server v6.1 to WebSphere Application Server v7.0 which is a complete upgrade and should be treated as such. The application migration from v6.1 to v7.0 may require library and API changes and API changes in order to take advantage of new functionality.

If you are coming from a competitive application server to WebSphere v7.0, the [IBM WebSphere Application Server Migration Toolkit] can assist you in this process.

In our test, we had a few API changes in our utility projects. Since we switched over to JPA 1.0 in the previous process, we can assume that newer versions of JPA when we upgrade should be able to run our 1.0 persistence.

Page 15: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1015

Update with new JPA 2.0 functionality

Now that we have WebSphere v7 installed and running with our JPA 1.0 application, we can apply the JPA 2.0 feature pack and utilize any of the new features that JPA 2.0 has to offer.

The WebSphere Application Server Information Center for the JPA Feature Pack has a few[Migration considerations when using JPA 2.0] when JPA 1.0 is your starting point. There are some areas of incompatibility, default behavior changes, and other non-specification related changes bteween the two versions.

JPA 2.0 gives the benefits of new functionality and performance.

Page 16: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1016

Comparable functions: Caching Hibernate may have L2 cache defaulted to “on”, but JPA does not.

However, it is not a difficult task to turn it on by setting a few things in your persistence.xml.

<properties> <property name="openjpa.DataCache" value="true"/> <property name="openjpa.RemoteCommitProvider" value="sjvm"/></properties>

This is just a very simple example. There are also many flavors of caching available for JPA which can be configured precisely with annotations or persistence.xml configuration.

Depending on your environment, you may look to using IBM eXtreme Scale to improve your performance.

Page 17: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1017

Comparable functions: Criteria API Multi-Criteria searches are very important in any type of user input

searching. Having them be dynamic is important, because you never know what the user may end up searching for. Eliminating the issue of testing each and every keyword and providing the ability to have any query created on the fly makes the Criteria API much more powerful, and in the long run, easier to code, and also has the advantage of being typesafe. With Criteria, you will be able to see incorrect queries during compile time instead of during runtime.

Page 18: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1018

Criteria API examples Let's examine the process of converting a Hibernate-specific version of Criteria to the new

JPA 2.0 implementation. Here is an old Hibernate Criteria query: // Hibernate classic Criteria API

List people = session.createCriteria(Person.class) .add(Expression.ge("age", age); // greater or equal to how old they are .add(Expression.eq("gender", gender); // their gender is equal to .addOrder( Order.asc("name") ) // order by alphabetical name .list();

Here is the new JPA 2.0 implementation. Note that there is no need to have specific string names in quotes. This reduces developer typing errors that would only be discovered during runtime.

// JPA 2.0 Criteria APICriteriaQuery<Person> cquery = cbuilder.createQuery(Person.class);Root<Person> person = cquery.from(Person.class); cquery.where( qbuilder.ge(person.get(Person_.age), age)); // greater or equal to how old they are cquery.where( qbuilder.eq(person.get(Person_.gender), gender)); // their gender is equal to cquery.orderBy( cbulder.asc(person.get(Person_.name))); // order by alphabetical nameTypedQuery<Person> query = em.createQuery(cquery);return query.getResultList();

Criteria is a powerful tool. To further understand the difference between JPQL and Criteria, see [Dynamic, typesafe queries in JPA 2.0].

Page 19: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1019

Using the enhancer JPA uses byte code enhancement to add persistence behavior to JPA

objects to enhance the actual Entity class objects. It's a way of tuning Java for JPA which in turn improves JPA performance.

You can set up your environment with a simple ANT script that runs the enhancer. To make the development process simpler, incorporate the Ant build as part of the Eclipse build.

This developerworks article will show you the way to setup this ant script inside your eclipse-based IDE. This way, when you compile your classes, the [JPA enhancer] will run as part of the build.

Page 20: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1020

Results After MigrationSince the Servlet we created has several reads and one write test, we have a 5:1 read/write ratio test. Each read test does up to 50 queries from the database, and each write test does 2 updates, including 2 queries to find the correct row to update. Our test's pattern of writing to a database infrequently and reading from it frequently was intended to simulate behavior with a typical website.

We found no deadlocks or memory leaks during our test after migrating the classic Hibernate application to JPA. WebSphere has been thoroughly tested with JPA, so you should feel confident in its stability.

Performance is a big factor in the persistence API you choose. JPA 2.0 has had significant improvements over its previous version. JPA 2.0 is also a significant improvement over Hibernate. Follow the alternate JPA provider instructions in your own environment to assess your performance improvement. See [Alternate JPA Providers in WebSphere Application Server] for details.

The steps covered in this report will make your application fit the JPA specification more closely than it did when using Hibernate. Moving to JPA as the standard on WebSphere will give you the features and performance of JPA 2.0, as well as the flexibility to use alternate providers if you still so desire.

Page 22: Migrating a Classic Hibernate Application to Use the ... · The Java Persistence API (JPA) is a great way to develop object-oriented Java applications with a relational database

WebSphere Application Server

© 2010 IBM Corporation05/28/1022

End

This page intentionally left blank