EJB Basics - by Example: Dave Landers BEA Systems, Inc

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

EJB Basics – By Example

Dave Landers
BEA Systems, Inc.

[email protected]
[email protected]
Agenda
EJB Overview
Parts of an EJB
Component Interface
Home Interface
Implementation
Deployment Descriptor
Writing simple EJBs
Limitations
Etc.
What is an EJB?
Enterprise Java Beans
Not JavaBeans
Architecture for server-side components
Lots of services provided for you by Container
Transactions, security, etc.
Most are declarative – no coding
You still have to think about and understand these services
You get a lot for a little work
Where is an EJB

Browser Swing App

JSP
Web Server
Server

EJB EJB

Database
EJB Features
Transactions
Security
Database
Distributed Components
RMI, CORBA
Container Managed Persistence
Performance and Scalability
Pooling, Load Balancing, etc.
Descriptor-Based Features
Deployment of new code to running server
Kinds of EJB
Session Beans
Entity Beans
Message Driven Beans

Each has its use


Coding is similar for each
Session Beans
Usually “business methods”
They do something
Often used to provide coarse grained access
Interact with several other EJBs, services, etc.
Two kinds
Stateless
Most common
Stateful
State maintained between method calls
State is “conversational” not “durable”
Think memory or files, not databases
Entity Beans
Usually represent “data”
Often stored in database
Durable persistence
Survives “crash” of container
Container- or Bean-Managed (CMP or BMP)
CRUD: Create, Read, Update, Delete
Unique Primary Key identifies individual Entities
Relationships to other Entities
Parts of an EJB
Home Interface
Factory for creating, finding, deleting EJBs
Looked up from JNDI
Component Interface
Client makes method call on these interfaces
Implementation Class
You write this to implement the EJB
Only the container calls it
Primary Key class for Entities
Deployment Descriptor(s)
Instructions to the container
Local vs. Remote
Remote
Distributed calls (RMI/CORBA)
Pass-by-Value (Serialized)
Local (EJB 2.0)
Must be in same JVM
Pass-by-Reference
No RemoteException
EJB can have Either or Both
Can have the Same or Different Methods
EJB Component Interface
Remote and/or Local
extend EJBObject or EJBLocalObject
Add your methods
Entities usually have get/set methods
Sessions usually have “operations”
If Remote, methods must throw java.rmi.RemoteEx-
ception
All arguments and return values for Remote must
be Serializable
EJB Home Interface
extends EJBHome or EJBLocalHome
One for each component interface
Requirements
Create methods (not required, but common for Entity)
Entity findByPrimaryKey
Optional
Several Create methods
Except jusr one for Stateless
Entity Beans
Other finders
Home Methods
The Implementation Class
Implements SessionBean or EntityBean
No difference in interface for Stateful / Stateless

Can Not implement Component or Home Interface


Not allowed
Method signatures differ slightly
Javac can’t help you get it right
Vendor “EJB Compiler” tools
IDE features
Errors when you deploy
Code Break
Simple Stateless Session Bean
HelloWorld
Only one method
String sayHello()
Local and Remote Interfaces
Only one implementation class
Writing the Implementation Class
Component Interface Methods
The business methods that do the work
Same signature
Do not throw RemoteException
Should pick a better Exception
Implementation...
Container Callbacks – called on state changes
Session Beans
setSessionContext
ejbCreate
Matches create(...) method(s) from Home
Only no-args for Stateless
ejbActivate, ejbPassivate
Used in Stateful only
ejbRemove
Code Break
Simple Stateful Session Bean
Counter
Keeps an int as State
One “business” method
int getNext()
{
return counter++;
}
Special things for Entity Beans
Primary Key Class
Identity for the instance – standard or custom class
Finders to do lookups (SQL SELECT queries)
findByPrimaryKey (required), findXXX (optional)
Return Remote/Local or Collection
Implementation returns PK or Collection of PK
Home Methods (EJB 2.0)
Not instance specific
Like static methods on an object
Prior to EJB 2.0, was usually in companion Session
Bean
Entity Bean Implementation...
Container Callbacks – called on state changes
setEntityContext, unsetEntityContext
ejbActivate, ejbPassivate
ejbCreate
Matches create(...) methos(s) from Home
BMP Entity – SQL INSERT, return Primary Key
ejbPostCreate – Entity Beans
Called after EJB created in Container – has identity
Do things that need EJB reference - establish relationships
ejbRemove
BMP Entity – SQL DELETE
ejbLoad, ejbStore
Entity Beans only – BMP SQL SELECT & UPDATE
Implementation...
Other Entity Home Methods
findByPrimaryKey, findXXX, other home methods
Similar signature as in Home
Method names prefix with “ejb” and next letter upper-cased

Return Types
Session ejbCreate() returns void
Entity ejbCreate() returns Primary Key type
BMP returns PK instance, CMP returns null
Entity ejbFindXXX() returns PK or Collection of PK
Entity Beans
– Container Managed Persistence
Abstract implementation class
Each “attribute” has abstract get/set methods
Implemented by the container
Mapping described in deployment descriptor
Bind finders to database using EJB-QL
Kind of like SQL
In deployment descriptor
Select Methods allow EJB-QL to be used from
home or business methods
Can also set up relationships with other Entity
Beans
Code Break
Simple Entity Bean
Property
Persists Key and Value pairs in Database
Container Managed Persistence
Entity Beans
– Bean Managed Persistence
You write the database code
JDBC and SQL in
ejbCreate, ejbRemove
ejbLoad, ejbStore
Finders, select methods
Maintain state of EJBObject vs. Database
Good if:
Binding is too complex for CMP / EJB-QL
Persistence is not to database
You are a control freak or have extra time....
Code Break
Property
Bean Managed Persistence
Extends CMP class and provides just persistence
methods
EJB Lifecycle
For All EJB Types: Stateless Session
Lifecycle of Instances
is manged by the Does Not Exist
Container
EJB gets callbacks at newInstance
setSessionContext() ejbRemove()
appropriate times
ejbCreate()

More State ==
More Complicated Method Ready Pool

method
Stateful Session Lifecycle
Does Not Exist System Exception
from any method
newInstance
setSessionContext() ejbRemove() timeout
ejbCreate()
ejbPassivate()
(LRU victim) Passive
Method Ready
ejbActivate()
(method)
method
Entity Lifecycle
ejbFindX() ejbSelectX()
newInstance
setEntityContext() ejbHomeX()
Pooled
unsetEntityContext()
Does Not Exist ejbRemove()
ejbActivate()
ejbCreate()
ejbPostCreate() ejbPassivate()

System Exception
from any method

ejbLoad() Ready ejbStore()

method ejbSelectX
About Exceptions
Throw any exception that makes sense

Application Exceptions
These are non-RuntimeExceptions
In your throws clause
You must handle things like rollback
System Exceptions
RuntimeException, Error (and subclasses)
Container must
Log it
Rollback transaction
Destroy bean instance
Deployment Descriptor
In EJB jar file: META-INF/ejb-jar.xml
Declares each EJB and
References to other EJBs (ejb-ref)
Environment Properties (env-entry)
Database and other resources (resource-ref)
Security restrictions
Transaction settings
CMP Definitions
Fields and Queries
Vendor specific Descriptor
Server specific configurations, tunings, etc.
Code Break
Deployment Descriptor for other examples
Client view of EJB
Lookup Home with JNDI
Create or find bean
Make method calls
Client EJB calls
Context jndiCtx = new InitialContext();
Might need JNDI properties for server connection

Object o = jndiCtx.lookup( “beanJndiName” );


MyLocalHome = (MyLocalHome)
jndiCtx.lookup( “localBeanJndiName” );

MyRemoteHome home = (MyRemoteHome)


PortableRemoteObject.narrow( o,
MyRemoteHome.class );
Narrow needed only if Remote
Use EJBHome to get EJBObject
MyEJB ejbObj = home.create();
MyEJB ejbObj = home.create( args );
MyEntity ejbObj = home.findByPrimaryKey( pk );
MyEntity ejbObj = home.findTheOne( ... );
Collection c = home.findTopTen( ... );
If Remote, objects retrieved from collection must be
Narrowed
Client etc.
ejbObject.remove()
When done with Stateful Session “conversation”
Not necessary for Stateless Session
Removes Entity from database

Don’t use equals()


ejbObject.isIdentical( EJBObject other )
For Entity or Stateful Session

ejbObject.getPrimaryKey()
Returns Entity PK
Code Break
Client code for examples
JSP
Message Driven Beans
No client interfaces (component or home)
Implement
MessageDrivenBean
javax.jms.MessageListener
One method:
onMessage(javax.jms.Message m)
Tied to JMS Destination when deployed
EJB 2.1 will let MDB receive non-JMS messages
EJB Limitations
No Read/write static fields
Might not be accessible by all EJBs
Container might spread across multiple JVMs
No Thread synchronization or thread management
Might not work like you think
Container spread across multiple JVMs
Mess up the container pooling, load balancing, etc.
No File I/O
Database is better
No Server sockets or multicast
No ClassLoader games or Native Library Loading
EJB Limitations
Usually OK for EJB to use objects that do these
things
But:
Read the rationale in the EJB spec
Chapter 24.1.2 – Programming Restrictions
Make sure you are aware of the reasons for the restric-
tions
Food for Thought:
What is a Singleton?
Consider distributed system, multiple ClassLoaders, multiple JVMs,
multiple computers....
EJB Limitations
Never give away “this”
Object reference to implementation
It “belongs” to the container
Get interfaces from SessionContext or EntityContext
and pass these around instead
context.getEJBObject()
context.getEJBLocalObject()
Design hints
Use locals where possible
Intra-server calls
Hide some things from Remote clients
Only deployed code has access
Use “queries” rather than “bulk” finders
If finder would return a lot
Finder returns EJBObject, might swamp container pool
Query as Home method returning PKs
Can use as needed
Or set up finder to return “reasonable sized” sets
Like cursor
Design hints
Entity Value Object
Serializable object representing state of Entity
Client can work with this rather than lots of remote
calls (individual get/set methods)
Entity has getValue / setValue
Consider where state is kept
Client (memory or HttpSession) vs. Stateful Session
Session Bean methods to access groups of EJBs
Rather than all on the client
Allows control of logic, transactions, security, etc.
What’s New – EJB 2.1
Expanded EJB-QL
Adds useful things SQL users are used to like ORDER
BY, MIN, MAX, SUM, COUNT, etc.
Timer Service
EJBs can get timed callbacks from container
Web Services
Stateless Session Beans as Web Services endpoints
JAX-RPC
Summary
Component Interface
Contract for the Component
Local and/or Remote
Home Interface
Factory
Create, Find, etc.
Implementation
Container Required Stuff
Your Code for Component and Home
Deployment Descriptor
Book Recommendations
Enterprise JavaBeans
Richard Monson-Haefel
Mastering Enterprise JavaBeans
Ed Rowman, et. al.
www.theserverside.com
Practical Java Programming Language Guide
Peter Haggar
Effective Java Programming Language Guide
Joshua Bloch
Mr. Bunny's Big Cup o' Java
Carlton Egremont III
Web References
EJB Spec
http://java.sun.com/products/ejb/docs.html
Go ahead, it’s only 572 pages
J2EE API Docs
http://java.sun.com/j2ee/sdk_1.3/techdocs/api
The Server Side
http://www.theserverside.com
News, Patterns, Discussion, Downloads, etc.
The End – Thank You
Please fill out evaluations

Example Code
On the conference CDROM
http://www.avitek.com/landers

[email protected]
[email protected]
More Implementation...
Container Callbacks – called on state changes
setSessionContext, setEntityContext, unsetEntityContext
ejbActivate, ejbPassivate
ejbCreate
Matches create(...) from Home
BMP Entity – SQL INSERT, return Primary Key
ejbPostCreate – Entity Beans
Called after EJB created in Container – has identity
Do things that need EJB reference - establish relationships
ejbRemove
BMP Entity – SQL DELETE
ejbLoad, ejbStore
Entity Beans only – BMP SQL SELECT & UPDATE
Basic Knowledge about EJB Page 1 of 6

Basic Knowledge about EJB

1. What is EJB?

EJB stands for Enterprise JavaBeans. EJB is a distributed object-oriented server component that makes
obsolete low-level APIs such as for component life-cycle management, transaction management, and
database processes, and enables the creation of server-side program components by simply writing
business logic processes. With Apdesigner, you can use Java to create server-side components (i.e.,
EJB) and client applications that use EJB. The EJB runtime environment absorbs transaction process
differences that might exist between the TP monitor and DBMS. It is possible to create non-platform-
dependent server program components.

The next section gives an overview of EJB.

Overview of EJB

EJB provides the following functions:

 Life-cycle management of enterprise bean instances


 Data persistence management
 Transaction management
 Security management
 Session management
 Resource management

To Top of Page

http://kr.fujitsu.com/products/solutions/ebiz_platform/was/technical/tutorial/ejb/kiso/kiso... 10/10/2010
Basic Knowledge about EJB Page 2 of 6

2. Applications that Can Be Created in Apdesigner

The following enterprise beans conforming to EJB1.1 or EJB2.0 contracts can be created with
Apdesigner.

 Enterprise JavaBeans
 Stateless Session Bean
 Stateful Session Bean
 Bean-managed persistence Entity Bean
 Container-managed persistence Entity Bean(*1)
 Point-to-Point model Message-driven Bean
 Publish/Subscribe model Message-driven Bean

*1 Container-managed persistence entity bean conforming to EJB1.1. Container-managed persistence


entity beans conforming to EJB2.0 are not supported.

To Top of Page

3. Overview of Developing Enterprise Bean in Apdesigner

1. To create a project in Apdesigner, select [Enterprise JavaBeans Project], and enter the required
information in the Enterprise Bean Wizard that creates enterprise bean model source and
deployment descriptor files.
2. When you create a model, the following files are created:
Type Generated File
enterprise bean source (java)
home interface source (java)
Session Bean
remote interface source (java)
deployment descriptor file (ejb-jar.xml)
enterprise bean source (java)
home interface source (java)
remote interface source (java)
Entity Bean
primary key class source (java) (*1)
record class source (java) (*1)
deployment descriptor file (ejb-jar.xml)
enterprise bean source (java)
Message-driven Bean
deployment descriptor file (ejb-jar.xml)

*1 These files are not always created depending on the options specified in the wizard.
3. Implement the Business method in the main source of the generated file.
4. Build the program using the Apdesigner and deploy it using the J2EE Deployment Tool.

To Top of Page

4. Points to Note Regarding the Creation of EJB Applications

http://kr.fujitsu.com/products/solutions/ebiz_platform/was/technical/tutorial/ejb/kiso/kiso... 10/10/2010
Basic Knowledge about EJB Page 3 of 6

1. Referring to the SQLServer when creating an entity bean persistence field

* Environment variable settings


Before starting Apdesigner, make the following environment variable settings:

PATH: Interstage-installation-folder\EJBCL\jdbc\bin
CLASSPATH: Interstage-installation-folder\EJBCL\jdbc\lib\fjisjdbc2.jar

For the environment variable settings of the machine on which Interstage Application Server is
installed, define the following settings:

PATH: Interstage-application-server-installation-folder\EJB\jdbc\bin
CLASSPATH: Interstage-application-server-installation-folder\EJB\jdbc\lib\fjisjdbc2.jar

* ODBC data source registration


Use the ODBC data source administrator to register the ODBC data source.
Use the system DSN for the ODBC data source.
Do not use the ODBC driver connection pooling function.
The correct version of the ODBC driver for running the JDBC driver is 2000.80.194.00 or later.

* Driver name and URL


Specify the following driver name and URL:

Driver name: com.fujitsu.interstage.jdbc.FJDriver


URL: jdbc:fjis:///ODBC_data_source_name

2. Developing an enterprise bean that calls another enterprise bean


An enterprise bean that calls another enterprise bean becomes a client application itself. The files
required for development and at runtime are listed below.
 For development:
 The class files of the home interface and remote interface of the enterprise bean that
is called
 The class files of any user-defined classes to be used with the interfaces of the
enterprise bean that is called
 At runtime:
 The class files used during development
 The stub files of the home interface and remote interface of the enterprise bean that is
called
The files required as stubs are generated as client distribution objects (at the time that the called
enterprise bean was deployed) in the location specified for 'Generation destination of Client file' in
the J2EE Deployment Tool.

3. Using a user-defined class included in another jar file from a enterprise bean
In order for an enterprise bean to use a user-defined class included in another jar file, it must be
possible to refer to the class during deployment of the enterprise bean. With the J2EE Deployment
Tool, you can specify CLASSPATH for referring to it.
4. Environment settings for developing EJB

http://kr.fujitsu.com/products/solutions/ebiz_platform/was/technical/tutorial/ejb/kiso/kiso... 10/10/2010
Basic Knowledge about EJB Page 4 of 6

Interstage Application Server is required for developing, deploying, and debugging EJBs.

<<Installation>>
For development in a client/server environment, the following Interstage Application Server client
functions must be installed:

- CORBA Service Client


- CORBA Service Development Tool
- Interstage EJB service client

Click [Install Client] from the Interstage Installer menu, and select and install the above functions.

<<CLASSPATH (build path) setting>>


For J2EE application development, Apdesigner provides Interstage J2EE Library as a
CLASSPATH container. The target jar file is set to the appropriate CLASSPATH (build path)
when a required function is selected.

<<IDL compiler environment setting>>


Since the IDL compiler is used for deployment, connections to the CORBA server must be able to
be established (it must be possible to refer to the repository on the CORBA server).
Write server information to Interstage-application-server-installation-folder\odwin\etc\inithost.
In addition, the required services of those listed below must be active on the server side. Start
Interstage Application Server to start the following types of services:

- Repository services
- Naming services
- CORBA services

5. If an error occurs during deployment

If the following problem occurs, check the items described below:

1) The following error occurs during deployment:


DEPLOY: Error: DEP2536: An error was detected in IDLc.: Detaile=05-002-0046

Check the following items:


- The required functions of Interstage Application Server are installed.
- The name of the machine on which Interstage Application Server is installed is specified
correctly in the inithost file.
- Interstage Application Server is active.

6. If an error occurs during execution of a client application

If one of problems listed below occurs, an environment setting is incorrect. Refer to Developing
Enterprise JavaBeans Client Applications and check the environment.

1) Error caused by failure to specify ORB

http://kr.fujitsu.com/products/solutions/ebiz_platform/was/technical/tutorial/ejb/kiso/kiso... 10/10/2010
Basic Knowledge about EJB Page 5 of 6

org.omg.CORBA.COMM_FAILURE: minor code: 1398079490

2) Error caused by an incorrect setting of inithost

jjavax.naming.NameNotFoundException: <lookup-identifier>

3) Error occurring because a client distribution object cannot be referred to from


CLASSPATH

java.lang.ClassCastException: [narrow()]

4) Error caused by failure to specify the environment property (java.naming.factory.initial)

jjavax.naming.NoInitialContextException: Need to specify class name in environment or system


property, or as an applet parameter, or in an application resource file: java.naming.factory.initial

5) Error caused by failure to start an enterprise bean

jjava.rmi.RemoteException: CORBA NO_IMPLEMENT 1179256960

7. Calling an enterprise bean on another server, with Plus Developer operating as a client

Normally, Interstage Apworks and Interstage Application Server clients can be installed in a
client/server environment for development and testing. However, for testing in a client/server
environment using Interstage Application Server Plus Developer, the environment for naming
services must be configured as described below.

Server functions are included in the installation of Interstage Application Server Plus Developer.
For this reason, to make Plus Developer operate as a client of another server instead of as a server,
the following batch program provided in Plus Developer must be run to switch the naming service
to be referenced:

Interstage-application-server-installation-folder\ISPLUS\bin\odmodifyns.bat

The procedure for switching the naming service is as follows:

1) Stop Interstage Application Server.


All services must be stopped by executing the Forced termination of all services.

2) Switch the naming service used for references by running odmodifyns.bat as follows:
- Switching to another server of a remote host
odmodifyns-remote-hostname [port-number]

- Referring to the local host

3) Start Interstage Application Server

http://kr.fujitsu.com/products/solutions/ebiz_platform/was/technical/tutorial/ejb/kiso/kiso... 10/10/2010
Basic Knowledge about EJB Page 6 of 6

To Top of Page

http://kr.fujitsu.com/products/solutions/ebiz_platform/was/technical/tutorial/ejb/kiso/kiso... 10/10/2010

You might also like