Sei sulla pagina 1di 48

EJB2.x to EJB3.

0 and JPA Migration


Soloman Barghouthi: Senior Software Engineer. WebSphere Architect.
Kevin Sutter: Senior Software Engineer. WebSphere Architect.
Roland Barcia: STMS: ISSW
Smarter Planet Solutions Require a Dynamic
Application Infrastructure

Smart Smart supply Smart Smart Smart Smart


industries chains countries weather regions cities

• Scale quickly and efficiently


• Optimize workload performance
• Flexibly flow resources
• Avoid downtime
• Save energy
• Automate management tasks
1
Dynamic Application Infrastructure
Builds on Smart SOA
Business Needs Adoption Patterns

“Meet business
objectives Application
consistently, nimbly, Foundation
cost-effectively”

“Enable applications Intelligent


to adapt to changing
market conditions” Management

“Address extreme Extreme


demands of clients & Transaction
business models”
Processing
2
Agenda

• EJB2x to EJB3.0 migration Tips and overview


• RAD 7.5 migration wizard
• Migration in action though a sample app

3
Overview

4
Recalling EJB 2.1 enterprise javabeans

Enterprise
JavaBeans

Entity Message- Session


Beans Driven Beans
Beans

CMP Stateful

BMP BMTD Stateless


CMTD 5
EJB 2.1 interface hierarchy

6
EJB 2.1 beans require deployment descriptors
• An EJB 2.1 deployment descriptor is an XML file that contains:
– Structural information about any EJBs that are part of the module
– A descriptor for container-managed relationships
– Declarations of all EJBs as <entity>, <session>, or <message-driven>
<ejb-jar>
<display-name>LegacyEJBs</display-name>
<enterprise-beans>
<entity>
<ejb-name>Customer</ejb-name>
...
</entity>
...
</enterprise-beans>
<relationships>
...
</relationships>
</ejb-jar>

7
Types of EJB 3.0 beans

Enterprise
JavaBeans

Session Message-
Beans Driven
Beans

Stateless Stateful

@Stateless @Stateful @MessageDriven 8

© Copyright IBM Corporation 2008


EJB 2.x session bean example
<session>
public interface ItemReserver
<ejb-name>ItemReserverImpl</ejb-name> extends EJBObject {
<home>ItemReserverHome</home> public void reserveItem(String isbn)
throws RemoteException;
<remote>ItemReserver</remote> }
<ejb-class>
com.ibm.ItemReserverImpl</ejb-class> public interface ItemReserverHome
extends EJBHome {
<session-type>Stateless</session-type> public void create() throws
<transaction-type> CreateException, RemoteException;
}
Container</transaction-type>
<resource-ref>
public class ItemReserverImpl implements
<res-ref-name>jdbc/libraryDB</res- ItemReserver, SessionBean {
ref-name>
protected ArrayList <String>
<res-ref-type> reserved = new ArrayList <String>();

javax.sql.DataSource</res-ref-type> public void ejbCreate()


<res-auth>Container</res-auth> throws CreateException

</resource-ref> public void reserveItem(String isbn){


</session> . . .}

... public void ejbActivate() { }

public void ejbPassivate() { }


} 9

© Copyright IBM Corporation 2008


EJB 2.x and EJB 3.0 session beans comparison
2.x 3.0
public interface ItemReserver extends EJBObject {
public void reserveItem(String isbn) throws @Remote
RemoteException;
} public interface ItemReserver{
public void reserveItem(String isbn);
}

@Stateful
public class ItemReserverImpl implements
public class ItemReserverImpl implements
ItemReserver, SessionBean { ItemReserver {
protected ArrayList <String> reserved = new ArrayList protected ArrayList <String> reserved =
<String> ();
new ArrayList <String> ();
public void reserveItem(String isbn){
. . .} public void reserveItem(String isbn){ ...
public void ejbActivate() { } }
public void ejbPassivate() { } @PostActivate
}
public void anymethod() { }
}

Object obj = @EJB


Context.lookup(“java:comp/env/ejb/ItemReservertH ItemReserver myReserver;
ome”);
ItemReserverHome resHome = (ItemReserverHome) obj;
ItemReserver myReserver = resHome.create(); myReserver.reserveItem(isbn);
myReserver.reserveItem(isbn);

10

© Copyright IBM Corporation 2008


EJB 2.x message-driven bean example
<message-driven>
<ejb-name>CopyReceiver</ejb-name>
public class CopyReceiver
<messaging-type> implements MessageDrivenBean,
javax.jms.MessageListener javax.jms.MessageListener {
</messaging-type>
<message-destination-type> private MessageDrivenContext
msgCtx;
javax.jms.Queue
</message-destination-type> public void onMessage(Message
<activation-config> msg) { . . . }
<activation-property>
<activation-config-property-name> public void
setMessageDrivenContext(
destinationType
MessageDrivenContext ctx ) {
</activation-config-property-name>
msgCtx = ctx;
<activation-config-property-value>
}
javax.jms.Queue
</activation-config-property-value> public void ejbCreate() {. . .}
</activation-property>
</activation-config> public void ejbRemove() {. . .}
</message-driven> } 11


© Copyright IBM Corporation 2008
EJB 3.0 message-driven bean example
@MessageDriven
public class CopyReceiver {

@Resource MessageDrivenContext ctx;


@EJB
LoanManager loanManager;
@EJB
PatronManager patronManager;

public void onMessage(Message msg) { . . . }


@PostContruct
Public void initialize(){ . . .}
}

12

© Copyright IBM Corporation 2008


Comparing JPA and EJB 2.x entity beans
• JPA offers standardized O/R mapping unlike CMP where each
vendor provided their own.
• Entities are not EJBs.
–They can be used in Java SE.
• Entities have a persistent identity distinct from their object
reference.
–This identity is obtained from the value of the primary key.
• Entities are not remotely accessible.
• The lifetime of an entity is not
necessarily related to the lifetime
of an application.
• Entities support disconnected operations

13

© Copyright IBM Corporation 2008


Migration and coexistence
• You can mix EJB 2.x and earlier beans with EJB 3.0 beans in
the same application.
–EJB 2.x or earlier beans and EJB 3.0 beans must not be
in the same module.
–EJB 2.x modules need a deployment descriptor.
–For EJB 3.0 modules, using deployment descriptors is
optional.

14

© Copyright IBM Corporation 2008


Migrating session beans to EJB 3.0 and affect on
clients.

• Two approaches to migrating EJB 2.x clients:


–Approach 1: Maintain backward compatibility with clients
• Implement a local home interface and remote home interface for
EJB 3.0 session beans.
• Use @LocalHome and @RemoteHome annotations on the bean
class to specify the home interfaces.
–Approach 2: Change the clients to look up the bean business
interface directly rather than going through the home interface
• Use a null value for the local-home or remote-home element
value and bind the ejb-local-ref or ejb-ref to the session
bean's JNDI binding.

15

© Copyright IBM Corporation 2008


Migrating session beans to EJB 3.0
• Example: Migrating EJB 2.x clients to use EJB 3.0 Session
beans
<ejb-local-ref id="EJBLocalRef_1154112538064">
<description>com.ibm.persistence.ejb3.order.facadecom.ibm.persi
stence.ejb3.order.facade</description>
<ejb-ref-name>ejb/OrderEJB</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type> <local-home></local-home>
<local>com.ibm.persistence.ejb3.order.facade.OrderProcessor</lo
cal>
</ejb-local-ref>

try {
InitialContext ctx = new InitialContext();
orderProcessor = (OrderProcessor)
ctx.lookup("java:comp/env/ejb/OrderEJB");
}
catch(Exception e) {
e.printStackTrace(System.out);
throw new ServletException(e);
} 16

© Copyright IBM Corporation 2008


JPA as a bridge to EJB 3.0
• Even if you do not use an EJB 3.0 container, you should use
JPA because:
–It is an easy-to-use programming model
–You will not need to rip and replace most of your work in the near
future
–Easily upgradeable to EJB 3.0
• Most of the work in using JPA will be in the annotating of your
entity classes.
–This will migrate easily to EJB 3.0.
• Your model should not change when you take the plunge into EJB
3.0.
• In EJB 3.0 you can have the container manage the EntityManager
objects automatically.

17

© Copyright IBM Corporation 2008


Mapping Options from Programming Model

• Options:
– Map DTO’s directly
• DTO’s are already POJO’s.
• Less work on the coding layer.
– Just annotate POJO’S or translate XML.
• If DTO does not match Entity Bean, then mapping will be difficult.

– Translate Entity Beans to POJO’s and map them.


• End up with multiple POJO’s. May involve eliminating POJO’s.
• Less work on the mapping layer if DTO does not match Entity
Bean.

18
DTO /Entity Bean Patterns – Pattern 1: Session Bean as translator

• Session Bean translates DTO to Entity Bean

19
Pattern 1: Session Bean as translator in JPA

• Map DTO to database


• Replace code in Session Bean that mapped DTO to CMP
with DTO to JPA Entity manager.
• Execute desired persistence operations on Entity Manager.
– Your DTO’s become the POJO’s you annotate.

20
DTO /Entity Bean Patterns – Pattern 2: Entity Bean as translator

• Session Bean passes DTO to Entity Bean within transaction


scope.

• Entity Bean moves data to fields.

21
Pattern 2: DAO as translator in JPA

• Entity Bean gets replaces by DAO.


• DTO is mapped to DB
• DAO passes POJO to Entity Manager

22
Pattern 3: Convert Entity Bean to POJO

• DTO and Entity Bean do not match (or no DTO)


• Convert Entity Bean to POJO
– Remove callbacks (or replace with Entity Listener) and interfaces.

23
Migration of mapping - WebSphere CMP

• Database Mapping
– XMI files cryptic, mapping happens with tooling.
– Fields
– Relationships
• Navigation, Cardinality
– Inheritance.

• Developer’s use tooling as main CMP mapping path


• JPA mapping is done more in the code.

• Use JPA tooling to generate bottom up mapping from


Database.

24
Entity Bean Mappings
OLD CMP TOOLS
• Old CMP tools
– Only path

• JPA

– RAD 7.5
• JPA Tools
from Eclipse
+ more
JPA Tools RAD 7.5
– Plain Annotation
Editor.

25
Converters and composers

Converters
At times, you might need to convert data that is read from a database
or saved to a database. Converters translate a database
representation to an object type, and they convert object types back
to database representations. For example, you might want to
convert a CHAR database entry 'Y' to a Boolean object set to true.
In this case, you can specify the VapStringToBooleanConverter in
the Properties view of the Mapping editor for the selected attribute
map.

Composers
A composer is used to map a single complex bean field to multiple
database columns. The complex field is a composed type.

26
JPA Custom Mappings

• Custom Class Mapping


To create a custom class mapping, write an implementation of the
org.apache.openjpa.jdbc.meta.ClassStrategy interface. You will probably want to extend one of
the existing abstract or concrete strategies in the org.apache.openjpa.jdbc.meta.strats package.
The org.apache.openjpa.persistence.jdbc.Strategy annotation allows you to declare a custom class
mapping strategy in JPA mapping metadata. Set the value of the annotation to the full class
name of your custom strategy. You can configure your strategy class' bean properties using
OpenJPA's plugin syntax

• Value Handlers
Value handlers make it trivial to map any type that you can break down into one or more simple
values. All value handlers implement the org.apache.openjpa.jdbc.meta.ValueHandler interface;
see its Javadoc for details. Also, examine the built-in handlers in the src/openjpa/jdbc/meta/strats
directory of your OpenJPA source distribution. Use these functional implementations as
examples when you create your own value handlers.

• Field Strategies
OpenJPA interacts with persistent fields through the org.apache.openjpa.jdbc.meta.FieldStrategy
interface. You can implement this interface yourself to create a custom field strategy, or extend
one of the existing abstract or concrete strategies in the org.apache.openjpa.jdbc.meta.strats
package. Creating a custom field strategy is more difficult than writing a custom value handler,
but gives you more freedom in how you interact with the database.

27
Isolation Levels

• Access Intents and Application Profile.


– WebSphere CMP strategy for locking
• Open JPA properties

<property name="openjpa.ReadLockLevel" value="none"/> <property


name="openjpa.WriteLockLevel" value="write"/> <property
name="openjpa.LockTimeout" value="30000"/>
• Locking API
EntityManager em = ...;
em.getTransaction().begin(); // load stock we know we're going to update
at write lock mode Query q = em.createQuery("select s from Stock s
where symbol = :s");
q.setParameter("s", symbol);
OpenJPAQuery oq = OpenJPAPersistence.cast(q);
FetchPlan fetch = oq.getFetchPlan ();
fetch.setReadLockMode(LockModeType.WRITE);
fetch.setLockTimeout(3000); // 3 seconds Stock stock = (Stock) …..

• WAS 7 Supports Access Intents for JPA

28
Caching

• Bean Caching

• Data Caching

• JMS based distributed cache

29
JPA Caching

• Data Cache

• Query Cache

• Cache Providers

30
Security

• CMP secured by role.


• JPA are just POJO’s.
– Secure wrapping Sessions
Beans instead

31
Agenda

• EJB2x to EJB3.0 migration Tips and overview


• RAD 7.5 migration wizard
• Migration in action though a sample app

32
RAD 7.5 new migration wizard

•Migration xmi to xml


•Migrate non CMP modules
from 2.x to 3.x

33
RAD 7.5 migration wizard

34
RAD 7.5 migration wizard

35
Agenda

• EJB2x to EJB3.0 migration Tips and overview


• RAD 7.5 migration wizard
• Migration in action though a sample app

36
Learn More About Dynamic Application Infrastructure!

Application Foundation
ibm.com/appfoundation

Intelligent Management
ibm.com/intellmgmt

Extreme Transaction Processing


ibm.com/xtp

ibm.com/appinfrastructure
37
Thank you for Attending. We Value Your Feedback !

• Please complete the session survey for this session by:

• Accessing the SmartSite on your smart phone or computer


at: http://imp2010.confnav.com
– Surveys / My Session Evaluations
• Visiting any onsite event kiosk
– Surveys / My Session Evaluations

• Each completed survey increases your chance to win an


Apple iPod Touch with daily drawing sponsored by
Alliance Tech

38
Questions?

39
Copyright and Trademarks

© IBM Corporation 2009. All rights reserved. IBM, the


IBM logo, ibm.com and the globe design are
trademarks of International Business Machines
Corporation, registered in many jurisdictions
worldwide. A current list of IBM trademarks is
available on the Web at "Copyright and trademark
information" at www.ibm.com/legal/copytrade.shtml.
Other company, product, or service names may be
trademarks or service marks of others.

40
Back up

41
JPA entity managers best practices
• Use the session façade pattern to manage JPA based persistence layer.
– Persistence management is free

• In EJB container, use container managed entity managers with container


managed transactions.
– Inject EntityManager using @PersistenceContext
– Container propagates persistence context and manages EntityManager lifecycle.
• Reduces the coupling of business methods to the persistence layer
– Enables cache, tx, etc… to be shared across EJB components.

• If you intend to keep your EJB 2.x session beans and only migrate the
persistence portion of your application from EJB 2.x CMP or JDBC to JPA.
– You cannot use injection of a persistence context and therefore must use the
application-managed entity manager.
– (You can still use CMT)

42

© Copyright IBM Corporation 2008


Relationships @Entity
Public class Customer
• ORM is for mapping {
– 80% access through mappings …
– 20% through JPQL or SQL. //Load Current order all the time
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="OPEN_ORDER",
• Explicitly specify fetch mode referencedColumnName = "ORDER_ID")
for relationships where protected Order openOrder;
default fetch mode is not
appropriate.
//order history accessed 15% of time
– Default fetch mode for
relationships @OneToMany(mappedBy="customer",
• One-to-one and Many-to-one: fetch=FetchType.LAZY)
Eager protected Set<Order> orders;
• One-to-many and Many-to-
many: Lazy
– Specify fetch based on
requirements.
– Explicitly specify the fetch
mode for the relationship
43

© Copyright IBM Corporation 2008


Business delegate pattern
• Use Business delegate? Is less necessary?
–Business delegate is a POJO
• Forces JNDI lookup over injection.
–Methods may map one to one with the business service methods
–Encapsulates lookup and access details
–Delegate method calls to an EJB component
–Hide exception handling
–Cache data locally
–Automatically retry
failed transactions

© Copyright IBM Corporation 2008 44


Data transfer object pattern
• Data transfer object (DTO) is a popular pattern with EJB 2.x.
– Enables transfer of data back and forth between remote clients and entity beans
– Intended for use with session façade pattern or session bean
• Enabled session facades to encapsulate access to entity beans
– Data can be the same as in the entity bean or coarse-grained
• Allow large quantities of data to be transmitted in a single network call
– Particularly useful for reading data from the server
• All the data required by the client can be obtained in one operation
– Can also be used for writing
• The client can create a DTO and send it to the server (using the Session Façade) to
perform an update

• DTOs are POJOs that are serializable.


•Cases when Domain Model is different?
– Use JPQL Shortcut?

45

© Copyright IBM Corporation 2008


DTO and detached entity pattern
• With EJB 3.0 entity EJBs are replaced by JPA entities.
• JPA entities are POJOs.
• Instead of DTOs, session facades can use the detached entity pattern
– Detached entity pattern allows for entities to be read in one transaction and
updated in another so that database locks are not held for long periods of
time.
• This is the typical usage pattern for many current Web applications.
• It is no longer necessary to create separate data transfer object classes for
communication between the tiers.
• DTO pattern is still applicable in some scenarios:
– Remote EJB
• Aggregate multiple objects
• Filter unnecessary attributes
• Customize view of data for the each client

46
– Local EJB
• Create aggregates and filters in IBM
© Copyright JSON, Web
Corporation 2008 Pages, or web service JAXB
Detached entity pattern
• JPA Entitles everywhere.

• When Session Bean


operated on them.
– They are Connected.

• When Web Tier operates


them
– Disconnected!! (Means no
DB operations implied)
• New World DTO
– JSON, ATOM, XML,
SOAP.
– Filter/Aggregate with
JAXB, ATOM API, JSON
API
47
– JPA Query
© Copyright IBM Corporation 2008

Potrebbero piacerti anche