Top Banner
© Copyright UTS Faculty of Information Technology EJB-1 Faculty of Information Technology Faculty of Information Technology Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part 2 – Entity & Message Beans Chris Wong [email protected] (based on prior class notes & Sun J2EE tutorial)
57

Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

Dec 20, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-1

Faculty of Information Technology

Faculty of Information Technology

Advanced Java Programming (J2EE)

Enterprise Java Beans (EJB)Part 2 – Entity & Message

Beans

Chris [email protected]

(based on prior class notes & Sun J2EE tutorial)

Page 2: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-2

Faculty of Information Technology

Faculty of Information Technology

Enterprise Java Beans

• Last lesson we looked at:– Introduction to EJB– EJB basics– EJB Architecture– Session Beans– EJB Clients– EJB Development Process

• This lesson will cover– Entity Beans– Message Driven Beans– EJB issues

Page 3: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-3

Faculty of Information Technology

Faculty of Information Technology

-Interlude-

• Earlier we discussed why we use EJB’s.

• EJB containers provide much of the ‘plumbing’ that traditionally programmers had to develop and consider themselves.

• We still need good programming practices to use EJB’s well.

• Use Design Patterns1 to re-use well known programming techniques.

• Good references:– 1 Gamma, E., R. Helm, R. Johnson, and J. Vlissides. “Design Patterns: Elements of

Reusable Object-Oriented Software”. Addison-Wesley 1995

– 2 Marinescu, Floyd “EJB design patterns” Wiley 2002

Page 4: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-4

Faculty of Information Technology

Faculty of Information Technology

The Session Façade pattern

• This is the most common design pattern used with EJB’s

• You partition business logic to minimise dependencies between client and server

• This optimises network traffic and executes as one transaction.

• Idea is to ‘wrap’ an entity EJB with a session EJB

• Only one interface between client and server• Completely hides ‘internal’ implementation

from client

Page 5: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-5

Faculty of Information Technology

Faculty of Information Technology

Traditional client/server

Marinescu, Floyd “EJB design patterns” Wiley 2002 Fig 1.2

Page 6: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-6

Faculty of Information Technology

Faculty of Information Technology

Session Façade

Marinescu, Floyd “EJB design patterns” Wiley 2002 Fig 1.2

Page 7: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-7

Faculty of Information Technology

Faculty of Information Technology

Session & Entity Beans

BankTeller- deposit()

- withdraw()

BankManager- openAccount()

Account - acctnum = 1234

- getBalance()- setBalance()

Account - acctnum = 2345

- getBalance()- setBalance()

Account - acctnum = 3456

- getBalance()- setBalance()

EJB container

Session Beans("actions")

Entity Beans("data")

Client(e.g.servlet)

DBMS

Page 8: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-8

Faculty of Information Technology

Faculty of Information Technology

Enterprise Java Beans

• Last lesson we looked at:– Introduction to EJB– EJB basics– EJB Architecture– Session Beans– EJB Clients– EJB Development Process

• This lesson will cover Entity Beans– Message Driven Beans– EJB issues

Page 9: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-9

Faculty of Information Technology

Faculty of Information Technology

Entity Beans

• Entity beans are EJBs that are created to encapsulate some data contained by the system (such as a row in the database or, more generally, to an entry that exists in persistent storage)

• Entity beans can be thought of as the “nouns” of a particular problem domain that they are implemented to solve

• The data can be created, searched for (found) or removed by clients

• The data can also be retrieved and updated by clients

Page 10: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-10

Faculty of Information Technology

Faculty of Information Technology

Entity Beans

• In addition to the usual EJB implementation, home interface and remote interface, Entity beans also have special primary key classes defined for them that relate to the primary keys of an associated entity stored in the database

• Entity beans are very different from Session beans. Entity beans:

– can be used concurrently by several clients– are long-lived – they are intended to exist beyond the

lifetime of a client– will survive server crashes– directly represent data in a database

Page 11: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-11

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – scalability

• Because clients could potentially hold many entity references as a result of a find operation, many effective EJB designs will only provide access to entity beans via session beans and limit how many entity bean handles are returned to the client

• Scalability of the system can become compromised if too many remote entity bean references are handed out to clients

• Articles describing various patterns for using entity beans are listed in the references

Page 12: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-12

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – container's role

• Entity beans assume that more than one client will use them concurrently. Interactions with the bean are moderated by the container so as to guarantee the integrity of the underlying data

• The container may accomplish this by either:– queuing client requests one at a time -- or --– creating an instance of the bean for each client and relying on the

underlying database to deal with synchronisation issues

• Remember, session beans do not support concurrent access. A stateful bean is an extension of the client and stateless beans don’t maintain state

• Entity beans (unlike Session beans) exist until they are explicitly destroyed:– There is no time out period associated with Entity beans– They are guaranteed to survive orderly server restarts – They are guaranteed to survive server crashes

Page 13: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-13

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – persistence• Entity beans represent data in an underlying database.

Their lifetime matches the lifetime of the underlying data

• Entity beans can be removed in one of two ways:– A client explicitly invokes the remove() method of the entity bean,

or– The data for the entity is deleted from the underlying database

• Entity beans typically map to data in an underlying database– Usually to a single row in a table.

The instance variables in the Entity bean map directly to the fields in the table.

• 2 Types of Entity beans– Bean Managed Persistence (BMP)– Container Managed Persistence (CMP)

Page 14: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-14

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – BMP vs. CMP

• Bean Managed Persistence (BMP) bean developer takes control of bean’s persistenceeg: use JDBC and SQL directly

• Container Managed Persistence (CMP) container manages the process of saving and restoring the state of beans.

Containers generate the code based on the information in the deployment descriptor for the bean.

Page 15: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-15

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – primary keys

• Each Entity bean instance has a primary key. • A primary key is:

– A value (or combination of values, called compound primary key) that uniquely identifies the entity

– Implemented as a Java class NOT a primitive (e.g., java.lang.Integer vs int)

• You can write your own class to represent a primary key– Must be serializable ie: implement the java.io.Serializable– Must have a no argument constructor– May have a constructor with the compound key values– Must implement a hashcode() and equals() method

– Easiest way is to use code generator to do this eg: Eclipse -> Source -> generate constructor from fieldsSource -> generate hashCode() and equals()

Page 16: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-16

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – primary keys

public class CustomerPK implements Serializable {public int custId;public String surname;

public CustomerPK(int custId, String surname) { ; // constructorthis.custId = custId;this.surname = surname;

}public int hashCode() {

final int PRIME = 31; int result = 1; result = PRIME * result + custId;result = PRIME * result + ((surname == null) ? 0 : surname.hashCode());return result;

}public boolean equals(Object obj) {

if (custId != other.custId) return false;} else if (!surname.equals(other.surname)) return false;return true;

}

}

Page 17: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-17

Faculty of Information Technology

Faculty of Information Technology

Entity Beans lifecycle

Does not exist

Pooled

Ready

ejbRemove()

ejbFind<METHOD>()

ejbPassivate()ejbActivate()

ejbStore()

ejbLoad()

Business method(s)

newInstance()

setEntityContext(ec)unsetEntityContext()

ejbCreate(args)

ejbPostCreate(args)

Page 18: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-18

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – lifecycle

• An entity bean can have one of three states:

– Does-not -exist state• not yet been instantiated. This state provides a beginning and

an end for the life cycle of a beans instance

– Pooled state• bean has been instantiated by the container but not associated

with an EJB object

– Ready state• it has been associated with an EJB object and is ready to

respond to business method invocations

Page 19: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-19

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – implementation

• Implementation of Entity beans is similar to that of session beans create a home interface, a remote interface and the bean implementation class

• The developer must also create the primary key class used to find instances of an existing bean. This primary key class is used as a parameter to the ejbFindByPrimaryKey() method Must be implemented by all entity beans

• All entity bean implementation classes must implement the javax.ejb.EntityBean interface (which extends javax.ejb.EnterpriseBean)

• The methods that need to be implemented depend on the persistence model you are implementing – BMP or CMP.

When using CMP the container will implement most of the methods for you

Page 20: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-20

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – methods

• Entity beans are created via the ejbCreate() method – this corresponds to an INSERT on the database

• Existing entity beans are loaded into the container via the ejbFindByPrimaryKey() method (and any other ejbFindXXXX() methods that may be defined) – these correspond to SELECT on the database

• Entity beans are removed via the ejbRemove() method – this corresponds to a DELETE on the database

• The container will call the ejbLoad() and ejbStore() methods when it needs to synchronise the state of the bean with the underlying database – these correspond to SELECT and UPDATE

• See the EJB specification and your text book for a complete reference of all the methods that exist on entity beans and the relevant configuration parameters that are defined in the deployment descriptor

Page 21: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-21

Faculty of Information Technology

Faculty of Information Technology

CMP vs. BMP

• CMP– Major change in EJB 2.0 (not compatible with EJB 1.1);

however, most containers support both versions– Don’t have to code the database access calls in the entity

bean• this makes bean portable across many database servers

– Many consider CMP is the default choice

• BMP– Given all the benefits of CMP, why someone bother with BMP?

• gives you more flexibility• can better accommodate a complex or unusual set of data• EJB 1.1 only supported BMP

– Cons• more work is required• ties the bean to a specific database type and structure

Page 22: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-22

Faculty of Information Technology

Faculty of Information Technology

Coding differences between Persistent Types

Difference CMP BMP

Class definition Abstract Not abstract

Database access calls Generated by tools Coded by developer

Persistent state Represented byvirtual persistentfields

Coded as instancevariables

Access methods forpersistent and relationfields

Required None

findByPrimaryKeymethod

Handled by container Coded by developer

Customized findermethods

Handled by containerbut the developermust define the EJBQL

Coded by developer

Select methods Handled by container NoneReturn value ofejbCreate

Should be null Must be the primarykey

Page 23: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-23

Faculty of Information Technology

Faculty of Information Technology

EJB 2.0 CMP Entity Bean (1)package bank;import javax.ejb.*;

public class abstract CustomerBean implements EntityBean {

SessionContext sessionContext;

// "Standard" session bean methodspublic void setSessionContext (SessionContext sc) {

this.sessionContext = sc;}public void ejbRemove() { }public void ejbActivate() { }public void ejbPassivate() { }

// continued on next page

Page 24: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-24

Faculty of Information Technology

Faculty of Information Technology

EJB 2.0 CMP Entity Bean (2)// continued from previous page

// Argument list must match create() method in home interfacepublic Integer ejbCreate(Integer id) {

setId(id); // call the usual setter methodreturn null;

}

// Now the business logic methods (as usual)

// Abstract get/set methodspublic abstract void setId(Integer id);public abstract Integer getId();

public abstract void setName (String name);public abstract String getName ();

}

Page 25: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-25

Faculty of Information Technology

Faculty of Information Technology

EJB 2.0 CMP Entity Bean (3)

• Entity EJB’s have additional parameters in the ejb-jar.xml Deployment Descriptor (DD)

<ejb-jar> <enterprise-beans> <entity>

// usual EJB stuff <ejb-name> Customer </ejb-name> <home> bank.CustomerBeanHome </home> <remote> bank.CustomerBean </remote> <ejb-class> bank.CustomerBean </ejb-class>

// set as CMP <persistence-type> Container </persistence-type>

// define primary key as Integer type <prim-key-class> java.lang.Integer </prim-key-class> <reentrant> False </reentrant>

// important! We are using CMP 2.0 <cmp-version> 2.x </cmp-version>

Page 26: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-26

Faculty of Information Technology

Faculty of Information Technology

EJB 2.0 CMP Entity Bean (4)

// continued from prior page

<abstract-schema-name>CustomerBean</abstract-schema-name>

// define the fields – these correspond to a column in the table

<cmp-field>

<field-name> Id </field-name>

</cmp-field>

<cmp-field>

<field-name> Name </field-name>

</cmp-field>

// define the primary key – the container generates findPrimaryKey() method!

<primkey-field> Id </primkey-field>

</entity>

</enterprise-beans>

… & so on

Page 27: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-27

Faculty of Information Technology

Faculty of Information Technology

EJB 2.0 CMP Entity Bean (5)

• You will also need 2 extra deployment descriptors– weblogic-ejb-jar.xml for weblogic specific parameters

– weblogic-cmp-rdbms-jar.xml how weblogic maps the datasource name and

table column names to the CMP bean.

See lab for details on this.

Page 28: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-28

Faculty of Information Technology

Faculty of Information Technology

Entity Beans – Summary

• Entity beans represent persistent data• Two types of entity beans:

CMP and BMP

• Entity beans must have a primary key class defined• BMP must provide database statements for:

– ejbCreate(), ejbRemove(), ejbFindByPrimaryKey(), ejbFindXXX() etc.

• More deployment descriptor (ejb-jar.xml) tags:– CMP fields (only for CMP EJBs)– Primary key class– Abstract schema name (only for EJB 2.0)

• Still need extra deployment descriptor for CMP entity beans (depending on the Application Server) to map bean to database table. weblogic-cmp-rdbms-jar.xml for WebLogic.

Page 29: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-29

Faculty of Information Technology

Faculty of Information Technology

EJB – Exception Types

• Note: javax.ejb.EJBObject and javax.ejb.EJBHome are subclasses of java.rmi.Remote. ie: your Home & Implementation will throw the

java.rmi.RemoteException from each of their methods (and you will need to catch them in your client !)

• There are other exceptions thrown by EJBs eg:– CreateException, DuplicateKeyException– FinderException, ObjectNotFoundException– RemoveException– EJBException, NoSuchEntityException

• EJB exceptions are depicted in the following figure:

Page 30: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-30

Faculty of Information Technology

Faculty of Information Technology

EJB – Exception Types (cont)

Perrone et al “Building Java Enterprise Systems with J2EE” Sams 2000 fig 36.2

Page 31: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-31

Faculty of Information Technology

Faculty of Information Technology

EJB – Exception Types (cont)

• EJBException – thrown by an EJB when an application specific method cannot be completed

• NoSuchEntityException – thrown by an EJB when an application specific method cannot be completed because a particular Entity bean does not exist

• CreateException – thrown when an EJB cannot be created (invalid arguments)

• DuplicateKeyException – a subclass of CreateException, thrown when a particular Entity bean cannot be created because objects with the same key already exist

• RemoveException – thrown when a particular EJB cannot be removed

• FinderException – thrown by all query methods (find or select) when an application error (business-logic) occurs

• ObjectNotFoundException – thrown when a singular EJB cannot be found

Page 32: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-32

Faculty of Information Technology

Faculty of Information Technology

Local Client API

• Only remote interfaces in EJB 1.1 • EJB 2.0 introduced local component interfaces• Local Interface

– Defines the bean’s business methods that can be used by other beans co-located in the same EJB container

– Allows beans to interact without the network overhead– Objects passed by reference rather than copied

• Local home interface– Defines the bean’s life cycle methods that can be used

by other beans co-located in the same EJB container

• Similar to Remote Client API but less complicated

Page 33: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-33

Faculty of Information Technology

Faculty of Information Technology

Local Interface

package bank;

import java.rmi.*;

import javax.ejb.*;

interface LocalBankTeller extends EJBLocalObject {

String sayHello();

void deposit(String acctnum, Float amount);

void withdraw(String acctnum, Float amount);

}

Notes:– Business logic methods for clients in the same

container– Note that none of the methods throw RemoteException– Identical to remote interface except for a couple of

differences

Page 34: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-34

Faculty of Information Technology

Faculty of Information Technology

Local Home Interface

package bank;

import java.rmi.*;

import javax.ejb.*;

interface LocalBankTellerHome extends EJBLocalHome {

public BankTeller create () throws CreateException;

}

Notes:– Note that none of the methods throw

RemoteException

Page 35: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-35

Faculty of Information Technology

Faculty of Information Technology

DD for Local Client

<?xml version="1.0"?>

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN' 'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>

<ejb-jar><enterprise-beans>

<session><ejb-name>BankTellerEJB</ejb-name><home>bank.BankTellerHome</home><remote>bank.BankTeller</remote><local-home>bank.LocalBankTellerHome</local-home><local>bank.LocalBankTeller</local><ejb-class>bank.BankTellerBean</ejb-class><session-type>Stateless</session-type><transaction-type>Container</transaction-type>

</session></enterprise-beans>…

</ejb-jar>

Page 36: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-36

Faculty of Information Technology

Faculty of Information Technology

Local Client API (cont’d)

• When to use Local Client API– When EJBs accessing each other from within the same

container

• Are local component interfaces necessary?– Some argue that local interfaces added more complexity– Most EJB1.1 vendors were already optimizing the Remote

Client API for co-located beans– You are locked into a single JVM

• However, local interfaces are here to stay– Container Managed Relationships† (EJB 2.0, CMP) need local

interfaces †Not covered in this subject

Page 37: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-37

Faculty of Information Technology

Faculty of Information Technology

EJB 2.0 CMP: EJB QL

• No standard language prior to EJB 2.0• EJB QL is a language similar to SQL-99• EJB QL statements are specified in the

deployment descriptor and the container will generate SQL

• EJB QL is an attempt to map Java objects and rows/columns

• Use EJB QL to:– Implement finders– Implement select methods– Navigate relationships

Page 38: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-38

Faculty of Information Technology

Faculty of Information Technology

EJB 2.0 CMP: EJB QL (2)

• Find methods are always declared in home interface

public interface CustomerHome extends EJBHome {

// findByPrimaryKey() is automatically generated by container

public Customer findByPrimaryKey(Integer pk)

throws FinderException, RemoteException;

// findByName() needs a query-method declared in the DD

public Customer findByName(String firstName, lastName)

throws FinderException, RemoteException;

}

• See http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBQL.html for a good tutorial on EJB-QL

Page 39: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-39

Faculty of Information Technology

Faculty of Information Technology

EJB 2.0 CMP: EJB QL (3)

• Query declaration in the bean’s DD <query>

<query-method><method-name>findByName</method-name><method-params>

<method-param>java.lang.String</method-params><method-param>java.lang.String</method-params>

</method-params></query-method><ejb-ql>

<![CDATA[SELECT OBJECT(c) FROM Customer c

WHERE c.lastName† = ?1 AND c.firstName = ?2]]>

</ejb-ql></query>

// †cmp name not shown

Page 40: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-40

Faculty of Information Technology

Faculty of Information Technology

Enterprise Java Beans

• Last lesson we looked at:– Introduction to EJB– EJB basics– EJB Architecture– Session Beans– EJB Clients– EJB Development Process

• This lesson will cover– Entity Beans Message Driven Beans– EJB issues

Page 41: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-41

Faculty of Information Technology

Faculty of Information Technology

Message Driven Beans

• Message-driven beans (MDBs) were introduced as part of EJB 2.0

• MDBs represent the integration of EJBs with JMS (the Java Message Service) – they handle incoming JMS messages

• JMS is an API for enterprise messaging by Sun Microsystems. JMS is not a messaging system itself; it’s an abstraction of the interfaces and classes needed by clients when communicating with messaging systems.

• MDBs act as a standard JMS message consumer. The Message-driven bean is a stateless component that is invoked by the EJB container as a result of receiving messages from a JMS Queue or Topic

• The MDB then performs business logic based on the message contents

Page 42: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-42

Faculty of Information Technology

Faculty of Information Technology

Message Driven Beans

• Unlike session or entity beans, MDBs have no home or remote interface, and therefore cannot be directly accessed by internal or external clients

• Clients interact with MDBs only indirectly, by sending a JMS message to a JMS Queue or Topic

• The EJB container automatically creates and removes MDB instances as needed to process incoming messages

• The goal of the MDB model is to ensure that developing an EJB that is asynchronously invoked to handle the processing of incoming JMS messages is as easy as developing the same functionality in any other JMS MessageListener

Page 43: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-43

Faculty of Information Technology

Faculty of Information Technology

Message Driven Beans

• Queue or Topic is defined in the deployment descriptor– message selector is also defined in DD - restrictive

• MDB must implement javax.jms.MessageListener and javax.ejb.MessageDrivenBean

• onMessage() must not throw JMS or application exceptions; instead they must be caught or handled. At least, they could be re-thrown as EJBException

• MessageDrivenBean specifies two methods:– ejbRemove()

• is invoked just before the bean is removed– setMessageDrivenContext(MessageDrivenBean ctx)

• sets the context for the bean

• ejbCreate() needs to be defined as well

Page 44: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-44

Faculty of Information Technology

Faculty of Information Technology

MDB Life Cycle

Does not exist

Ready poolonMessage()

newInstance()

setMessageContext(mdc)

ejbCreate() ejbRemove()

Page 45: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-45

Faculty of Information Technology

Faculty of Information Technology

Example – Message-driven bean

import javax.ejb.*;

import javax.jms.*;

public class MessageTraderBean implements MessageDrivenBean, MessageListener {

public void ejbCreate () throws CreateException { … }

public void ejbRemove() { … }

public void setMessageDrivenContext(MessageDrivenContext ctx) { … }

public void onMessage(Message msg) {

try {

// process message

}

catch (EJBException ex) { … }

}

}

Page 46: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-46

Faculty of Information Technology

Faculty of Information Technology

Example – Message-driven bean ejb-

jar.xml <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans

2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">

<ejb-jar> <enterprise-beans> <message-driven> <ejb-name>exampleMessageDriven</ejb-name> <ejb-class>examples.ejb20.message.MessageTraderBean</ejb-class> <transaction-type>Container</transaction-type> <message-driven-destination> <jms-destination-type>javax.jms.Topic</jms-destination-type> </message-driven-destination> <security-identity> <run-as-specified-identity> <role-name>foo</role-name> </run-as-specified-identity> </security-identity> </message-driven></enterprise-beans></ejb-jar>

Page 47: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-47

Faculty of Information Technology

Faculty of Information Technology

Enterprise Java Beans

• Last lesson we looked at:– Introduction to EJB– EJB basics– EJB Architecture– Session Beans– EJB Clients– EJB Development Process

• This lesson will cover– Entity Beans– Message Driven Beans EJB issues

Page 48: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-48

Faculty of Information Technology

Faculty of Information Technology

EJB – Clustering Issues

• Highly scalable, mission critical enterprise applications will inevitably require more than a single application server to deliver services with minimal downtime and maximum performance

• In these environments, clustering is used to guarantee availability and scale to meet the demands placed on the system

• A cluster is a group of application servers that transparently run your J2EE application as if it was a single entity

• Scaling is accomplished by adding extra machines to the cluster. Multiple machines provide redundancy that increases availability

Page 49: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-49

Faculty of Information Technology

Faculty of Information Technology

EJB – Clustering Issues (cont)

• Clustering support isn’t defined in the J2EE specification – application server vendors are left to implement clustering in whatever manner they see fit

• Most J2EE application servers implement clustering around their implementation of JNDI.

1. Independent – each app server has its own independent JNDI tree

2. Centralised – a single, centralised JNDI tree is maintained for all app servers

3. Shared Global – each app server shares a global JNDI tree with the cluster. All objects bound into the JNDI tree are broadcast to all servers in the cluster. This is the mechanism used by WebLogic

Page 50: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-50

Faculty of Information Technology

Faculty of Information Technology

EJB – Clustering Issues (cont)

• You do have to be aware of how clustering is implemented in your application server when deploying a J2EE application to a cluster

• The relevant deployment properties will be container specific

• See the WebLogic server documentation for a description of how clustering of EJBs (and web applications) is configured

• Note that there are some limitations introduced when deploying to a cluster (particularly for stateful session beans) – however these are still preferable to running a single application server with no redundancy or failover capability

Page 51: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-51

Faculty of Information Technology

Faculty of Information Technology

EJB Key Features Summary

– They provide a model for defining server-side components

– They provide a model for defining distributed client interfaces to the services provided by these components

– They provide standard operations and semantics for allowing a container to create, destroy, allocate, persist and activate component instances

– They provide a standard model for defining a component that maintains a conversational session with a client, with session management handled by the container

– They provide a standard model for defining a component that encapsulates a data source (such as a database) entry, with object-relational mapping handled by the container

Page 52: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-52

Faculty of Information Technology

Faculty of Information Technology

EJB Key Features Summary

• EJB key features (continued):

– They provide a standard for defining configuration and deployment characteristics of a component, independent of its implementation

– They provide a standard model for declaratively defining the security attributes of a component

– They provide a standard model for declaratively defining the transactional attributes of a component

– They provide a standard component interface contract such that components can run in any EJB-compliant container/server that implements the standard interface contract

Page 53: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-53

Faculty of Information Technology

Faculty of Information Technology

EJB’s - Cautions

• EJB 1.1 only had remote interfaces. This meant that clients had to use the network to connect to EJBs, even on the same physical server!!

use Local interface instead. + new EJB-QL and selector methods available.– But this means the session bean will run in the same Java VM

as the entity bean!

• Use EJBs where appropriate EJB containers have high overhead (and cost $$).

• Sometimes using lightweight Web Containers such as Tomcat + JDBC/stored procedures is more appropriate.

• Java Data Objects (JDO) provides an alternative mechanismSee http://java.sun.com/products/jdo/index.jsp

Page 54: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-54

Faculty of Information Technology

Faculty of Information Technology

Alternatives?

• Java EE 5 has new persistence mechanism– Based on Java 5 annotations

Java Persistence API (JPA)

• EJB 3.0 based on JPA

• You can also use open source products such as Hibernate (which has a JPA interface) or commercial products such as Oracle Toplink

Page 55: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-55

Faculty of Information Technology

Faculty of Information Technology

EJB 3.0

• Just plain old Java Objects! Eg: BankTeller:

@remotepublic interface BankTellerRemote {

public string sayHello(String name);}

@stateless(name=“BankTeller”)public class BankTeller implements BankTellerRemote {

public string sayHello(String name) {return “Hello, “ + name;

}}

• Note: no XML, no “housekeeping” code!

Page 56: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-56

Faculty of Information Technology

Faculty of Information Technology

EJB 3.0 persistence

• Eg: Account

@Entity@Table (name=“Accounts”)@NamedQuery ( name = “findByAcct”,

query=“select Object(a) from Accounts where a.acct = ?1”)

public class Account implements Serializable {

@Id // next field is primary key @column (name=“Acct”)

public Integer getAcctNum() { … }

@column (name=“Balance”)public float getBalance() { … }

Page 57: Faculty of Information Technology © Copyright UTS Faculty of Information TechnologyEJB-1 Advanced Java Programming (J2EE) Enterprise Java Beans (EJB) Part.

© Copyright UTS Faculty of Information Technology EJB-57

Faculty of Information Technology

Faculty of Information Technology

Summary

• The past two lessons have introduced the component model for Java enterprise applications – Enterprise Java Beans

• We have touched on a number of aspects of EJB architecture and development

• You should now understand the different types of EJB, when they should be used, how they are developed and deployed, and how they are used from client applications

• EJBs are a fairly complex topic, and you will need to do additional study to fully understand the intricacies of EJB design and development