30
1 Soo Dong Kim, Ph.D. Object Technology Laboratory Tel. 820-0909 Fax. 826-0909 [email protected] object.soongsil.ac.kr Feb. 14, 2001 EJB Key Concept EJB Key Concept EJB Key Concept ©2000 Soo Dong Kim 2 Contents Contents EJB Overview Session Bean Stateless Session Bean Stateful Seesion Bean Entity Bean Bean-managed persistence Container-managed persistence Transaction

EJB Key Concept

Embed Size (px)

Citation preview

Page 1: EJB Key Concept

1

Soo Dong Kim, Ph.D.Object Technology LaboratoryTel. 820-0909 Fax. 826-0909

[email protected] object.soongsil.ac.kr

Feb. 14, 2001

EJB Key ConceptEJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

2

ContentsContentsEJB OverviewSession Bean

Stateless Session BeanStateful Seesion Bean

Entity BeanBean-managed persistenceContainer-managed persistence

Transaction

Page 2: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

3

TerminologyTerminologyEnterprise JavaBeans

Is an architecture for component-based distributed computing.

Enterprise BeansAre components of distributed transaction-oriented enterprise application.

EJB Key Concept

©200

0 S

oo D

ong

Kim

4

Enterprise JavaBeans (EJB)Enterprise JavaBeans (EJB)Enterprise JavaBeans

EJB define how server-side components are written and provides a standard contract between components and the application servers that manage them.EJB promote the spawning of a component marketplace, where vendors can sell reusable components that can be purchased to help solve business problems.

Page 3: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

5

A server-side component architecture Allows developers to quickly create scalable enterprise applications using javaProvides complex middleware enterprise features at no cost

Transactions, persistence, security, state management, threading

Cross-platform, cross-vendorThere is one standard, allowing the vendors to focus on the quality of their EJB products.

Enterprise JavaBeansEnterprise JavaBeans

EJB Key Concept

©200

0 S

oo D

ong

Kim

6

Enterprise BeansEnterprise BeansEssential characteristics :

An enterprise Bean contains business logic.An enterprise Bean’s instances are created and managed at runtime by a container.An enterprise Bean can be customized at deployment time by editing its environment properties.Various metadata, such as a transaction mode and security attributes, are separated out from the enterprise Bean class.

Page 4: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

7

Enterprise BeansEnterprise BeansClient access is mediated by the container and the EJB server.If an enterprise Bean uses only the standard container services, the enterprise Bean can be deployed in any EJB container.Specialized containers can provide additional services.An enterprise Bean can be included in a composite application without source code changes or recompilation.

EJB Key Concept

©200

0 S

oo D

ong

Kim

8

RolesRolesEnterprise JavaBeans architecture

Defines six distinct roles in the application development and deployment life cycle.

Enterprise Bean ProviderAn application domain expertDevelops reusable components called enterprise Beans.

Application AssemblerCombines enterprise beans into larger deployable application units.Output is one or more ejb-jar files that contain the enterprise beans with their application assembly instruction.

Page 5: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

9

RolesRolesDeployer

An expert at a specific operational environment.Is responsible for the deployment of enterprise Beans and their containers.

EJB Server ProviderA specialist in the area of distributed transaction management, distributed objects, and other lower-level system-level services.

EJB Container ProviderThe expertise of a container provider is system-level programming, possibly combined with some application-domain experts.

System AdministratorThe role of a system administrator is to oversee the well-being of a running system.

EJB Key Concept

©200

0 S

oo D

ong

Kim

10

Roles MapRoles Map

EJB Server Provider

Administrator

manage

Bean Provider

Application assembler

Container Provider Deployer Tool

EJB-JARs

Combine

Assembly Instructions

Page 6: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

11

EJB ContractsEJB ContractsClient’s view contract

Contract between a client and a container.Includes

Home interfaceDefines the methods for the client to create, remove, and find EJB Objects.Client locates an home interface through the JNDI API.

Remote InterfaceDefines the business methods callable by the client.

Object identityContainer must generating a new unique identifier for each Session Object.The identifier is not exposed to the client.Bean Provider must supply a primary key at Entity Object creation time

Metadata interfaceHandle

EJB Key Concept

©200

0 S

oo D

ong

Kim

12

EJB ContractsEJB ContractsComponent contract

An enterprise Bean class instance’s view of its life cycle.javax.ejb.SessionContext interface that a container passes to a session enterprise Bean instance at instance creation.Environment java.util.Properties that a container makes available to an enterprise Bean.List of services that every container must provide for its enterprise Beans.

Page 7: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

13

EJB ContractsEJB Contracts

Enterprise Bean

Container

ContainerContract

EJB Server

ClientClient’s view Contract

EJB Key Concept

©200

0 S

oo D

ong

Kim

14

Enterprise BeansEnterprise BeansTypes of Enterprise Beans

Session BeanStateless session beanStateful session bean

Entity BeanBean-managed persistentContainer-managed persistent

Page 8: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

15

Session Bean OverviewSession Bean OverviewSession Bean

Non-persistent objectIs a logical extension of the client program that runs on the server.Is not shared among multiple clients.

LifetimeMight live for minutes or hours

but probably not weeks, months, or years.

Session beans are no persistent.Not saved to permanent storage.

EJB Key Concept

©200

0 S

oo D

ong

Kim

16

Session Bean OverviewSession Bean OverviewStateless Session bean

Store no conversational state from method to method.Easily reused by multiple clients rather than destroyed and re-created per client.

Stateful Session beanComponents that hold conversations with clients.

Page 9: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

17

Session Bean OverviewSession Bean OverviewAll the functionality for remote access is provided by the container.

Security, concurrency, transactions,swapping to secondary storage

Each session EJB object has an identity Which does not survive a crash and restart of the container.

Multiple EJB classes can be installed in a container.Container allows the clients to look up the home interfaces via JNDI.Home interface provides methods to create and remove the EJB objects.

EJB Key Concept

©200

0 S

oo D

ong

Kim

18

EJB ContainerEJB ContainerIs a system that functions as the “container” for enterprise Beans.Client look up the home interface for the EJB class using JNDI.

By the container

Container is where an Enterprise Bean object lives.

A record lives in a databaseA file or directory lives in a file system

Page 10: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

19

EJB ContainerEJB Container

EJB class 1

EJB class 2

Container

EJB objects

EJB objects

EJB Home

EJB Home

Other EJB Classes

Client

EJB Key Concept

©200

0 S

oo D

ong

Kim

20

Home InterfaceHome InterfaceEJB Container implements the home interface of each enterprise Bean.

The container makes the home interface available to the client through JNDI.

Home interface allows a client to do Create a new EJB object.Remove an EJB object.Get the EJBMetaData interface for the enterprise Bean.Obtain a handle for the home object.

The home handle can be serialized.

Page 11: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

21

EJB objectEJB objectA client never accesses instances of the enterprise Bean’s class directly.

Uses the enterprise Bean’s remote interface.

An EJB object supports Business logic methodsMethods of the javax.ejb.EJBObjectinterface(is implemented by the container).

Get the EJB object’s container.Get the EJB object’s handle.Test if the EJB object is identical with another EJB object.Remove the EJB object.

EJB Key Concept

©200

0 S

oo D

ong

Kim

22

Session object identitySession object identitySession objects hide their identity.

Entity objects expose their identity as a primary key.Result in java.rmi.RemoteException

EJBObject.getPrimaryKey() and EJBHome.remove(Object primaryKey) methods

java.lang.RuntimeExceptionWhen the EJBMetaData.getPrimaryKeyClass() is invoked on a meta-data object for a Session Bean.

Page 12: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

23

Session object identitySession object identitySince all session objects hide their identity,

There is no need to provide a finder for them.Home interface for a session object must not define any finder methods.

Session EJB object handle can be held beyond the life of a client process

By serializing the handle to persistent store.

EJB Key Concept

©200

0 S

oo D

ong

Kim

24

ClientClient’’s view of Session Beans view of Session Bean’’s life cycles life cycle

Does not exist and

not referenced

Exists and

not referenced

Does not exist and

referenced

Exists and

referenced

Release reference

Container crash,or bean timeout

Handle.getEJBObject( )

Release reference

home.create(…) object.remove(),home.remove(…),system exception in bean,bean timeout, orContainer crash

Client’s method on reference

Client’s method on referencegenerates java.rmi.NoSuchObjectException

Page 13: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

25

Object identityObject identityStateful Session Beans

has a unique identity that is assigned by the container at create time.isIdentical(Object otherObject)

Stateless Session BeansAll EJB objects have the same object identity.The isIdentical(Object otherObject) always returns true.

Type narrowingjavax.rmi.PortableRemoteObject.narrow(...)

EJB Key Concept

©200

0 S

oo D

ong

Kim

26

Stateless Session BeanStateless Session BeanNo Conversational State

Not customized for a particular client.

Only One Way to Initialize Initialized with ejbCreate(), which takes no parameters.

Pool and ReuseContainers can pool instances before clients connect. Support dynamically resizable pools over time.

EJB Object DecouplingReassigned at any time to another EJB object.Important to know when debugging EJB applications.

Page 14: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

27

StatefulStateful Session BeanSession BeanConversational Beans

They hold conversations with clients that span multiple method invocations.They store conversational state within the bean.That conversational state is specific to a particular client.

EJB Key Concept

©200

0 S

oo D

ong

Kim

28

Effect of PoolingEffect of Pooling ((StatefulStateful Session Bean)Session Bean)

Pooling is not as simple as Stateless Session. Each bean is storing state on behalf of a particular clients therefore container can’t easily pool beans and dynamically assign.

EJB containers exploit the swapping paradigm .

To conserve stateful session bean resourcesPassivation - Swap out

After passivation, allow resources to be reclaimed.

Activation - Swap inThe bean resumes the conversation with the original client.

Page 15: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

29

Effect of PoolingEffect of Pooling ((StatefulStateful Session Bean)Session Bean)How does the container decide which beans to activate/ passivate?

To passivate beansSpecific to each container

Mostly LRU strategy

Container decides when passivation makes sense.One exception

any bean involved in a transaction can’t be passivated

until the transaction completes .

To activate beans

Most containers will use a just-in-time algorithm.Beans should be activated on demand, as client requests come in.

EJB Key Concept

©200

0 S

oo D

ong

Kim

30

PassivationPassivation of of StatefulStateful Session BeanSession Bean

EnterpriseBean

Other Enterprise Beans

EJB Object

2. Pick the least recently used bean

3. Call ejbPassivate()

4. Serialize the bean state

Client

Remote Interface

1.Involve business method

Storage

5. Store passivatedbean state

Page 16: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

31

Activation of Activation of StatefulStateful Session BeanSession Bean

EnterpriseBean

Other Enterprise Beans

EJB Object

3.Reconstruct bean

4.Call ejbActivate()

5. Invoke business method

Client

Remote Interface

1.Involve business method

Storage

2. Retrieve passivatedbean state

EJB Key Concept

©200

0 S

oo D

ong

Kim

32

Entity Beans OverviewEntity Beans OverviewEntity Beans

A component that represents such persistent data.Do not contain business process logic.Multiple clients can use entity beans simultaneously.Does not perform complex tasks or workflow logic.

LifetimeLonger than a client’s sessionDepending on how long the data sits in the database.

Page 17: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

33

Features of Entity BeansFeatures of Entity BeansLong-lived.Survive failures.Entity bean instances are a view into a database.Several entity bean instances may represent the same underlying data.Entity bean instances can be pooled.Entity beans can be created, removed, or found.Entity beans can represent legacy data and legacy systems.Entity beans can be modified without going through EJB

EJB Key Concept

©200

0 S

oo D

ong

Kim

34

View into a DatabaseView into a DatabaseejbLoad( )

Reads the data in from the persistent storage into the entity bean’s in-memory fields.

ejbStore( )Saves your bean instance’s current fields to the underlying data storage.

Page 18: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

35

Can be PoolCan be PoolEntity bean may be holding resources

Socket connections.

ejbActivate( )When transitioning your bean out of a generic instance pool.

Callback that your container will invoke on your bean instance.

ejbPassivate( )When transitioning your bean into a generic instance pool.

Callback that your container will invoke.

EJB Key Concept

©200

0 S

oo D

ong

Kim

36

PassivationPassivation and Activationand ActivationContainer

1: ejbStore()

2:ejbPassivate()

1:ejbActivate()

2:ejbLoad()

Passivation entails a state save.

Activation entails a state load.

Bean Instance

Page 19: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

37

Creation of Entity BeansCreation of Entity BeansejbCreate()

Do not need to write any ejbCreate( ) methods with entity beans.

Session beans require ejbCreate() methods.Via direct database inserts or legacy systems.Is optional.

Parameters to ejbCreate() can vary.Multiple ways to initialize an entity bean instance.

Duplicate methods in your home interface.Define a corresponding create() in the home interface.

EJB Key Concept

©200

0 S

oo D

ong

Kim

38

Creating Entity Bean.Creating Entity Bean.

Client Code

EJB Object

EnterpriseBean

EJB Container/Server

Home Object1: create()

5: Create EJB object

Entity beandata

6:return EJB object

2:ejbCreate()

4:return primary key

3:Create database data

Page 20: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

39

Entity BeansEntity BeansejbFind( )

Uses to find an existing entity bean in storage.Finder methods do not create any new database data.

ejbRemove()To destroy an entity bean’s data in a database.Does not mean the in-memory entity bean instance is going to be destroyed.There is only one form of ejbRemove().Is not called if the client times out.

EJB Key Concept

©200

0 S

oo D

ong

Kim

40

Entity Bean life cycleEntity Bean life cycleDoes not

exist

pooled

ready

Instance throwssystem exceptionfrom any method

1. unsetEntityContext()

ejbFind<METHOD>()

ejbStore()ejbLoad()

Business method

ejbActivate()ejbPassivate()

ejbRemove()ejbCreate(args)ejbPostCreate(args)

1. newInstance()2. setEntityContext(ec) 2. JVM will garbage collect

And call finalize()

Page 21: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

41

BeanBean--managed persistencemanaged persistenceCharacteristic :

Entity bean that must be persisted by hand.Hard-code database access with in class.

You must write to a persistence API.

Not automated, developer manually creates mapping through JDBC calls.Entitity bean provider implement the entity bean’s persistence directly

Object PersistenceData access protocol for transferring the state of entity between the entity bean instances and the underlying database

EJB Key Concept

©200

0 S

oo D

ong

Kim

42

ContainerContainer--managed persistencemanaged persistenceCharacteristic :

Automatic persistence for your entity beansThe container/server performs every function of your component’s data access layer.Theoretical database independenceThe container provides tools that generate code in the EJB class.The bean provider must specify in the deployment descriptor the list of the instance fields for which the container provider tools must generate access calls.

Page 22: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

43

ContainerContainer--managed fieldsmanaged fieldsContainer-managed persistent entity bean

Allows the container to handle some or all of its data access logic.

Container implicitly perform all database operations behind the scenes.

Must make some of entity bean class’s fields public.

Container can set the fieldsWhen it performs database operations on behalf of your bean.

EJB Key Concept

©200

0 S

oo D

ong

Kim

44

Entity Beans can be modified.Entity Beans can be modified.Modified without going through EJB

Existing App

Entity Beandata

Entity Bean

EJB Container/Server

O/R Mapping Direct Database Modifications

Page 23: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

45

TransactionsTransactionsConcept

Appear to execute as one large, atomic operationGuarantee an all-or-nothing value proposition

All of your operations will succeed, or none of them will.

Allow multiple users to share the same dataGuarantee that any set of data they update will be completely .

EJB Key Concept

©200

0 S

oo D

ong

Kim

46

The Motivation for TransactionsThe Motivation for TransactionsA few motivational problems that transactions address

Atomic OperationNetwork or Machine FailureMultiple Users Sharing Data

Page 24: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

47

The ACID PropertiesThe ACID PropertiesAtomicity

If interrupted by failure, all effects are undone.Operations performed within a transaction undergo an all-or-noting paradigm.

ConsistencyEffects of a transaction preserve invariant properties.A transaction will leave the system’s state to be consistent after a transaction completes.

EJB Key Concept

©200

0 S

oo D

ong

Kim

48

The ACID PropertiesThe ACID PropertiesIsolation

Intermediate states are invisible to others.Without isolation, your application state may become inconsistent.Locks on data are automatically assigned as necessary.

DurabilityEffects of a transaction are persistent.Updates to managed resources, such as database records, survive failures.

Page 25: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

49

Transactional ModelsTransactional ModelsFlat Transactions

Performed atomically as a single unit of work.Decide to end the transaction

Successful transaction is committed.All of the persistent operations become permanent changes.

Failed transaction is aborted.All changes are rolled back

Your application may have performed are automatically undone by the underlying system.

EJB Key Concept

©200

0 S

oo D

ong

Kim

50

Transactional ModelsTransactional ModelsThe Flat Transaction Process

TransactionOccurring

Final State(Transaction Rolled Back)

Begin transaction

If all goes well, commit transaction

If problem occurs,Abort transaction

Final State(Transaction Succeeded)

Initial State(No Transaction Occurring)

Page 26: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

51

Transactional ModelsTransactional ModelsNested Transactions

Allows you to embed atomic units of work within other units of work.

The unit of work is nested within another unit of work can roll back without forcing the entire transaction to roll back.

If the embedded unit can be made to succeedthe larger unit can succeed.

If the embedded unit of work cannot be made to work

ultimately force the entire unit to fail.

EJB Key Concept

©200

0 S

oo D

ong

Kim

52

Transactional ModelsTransactional ModelsThe Nested Transaction Process

TransactionOccurring

Final State(Transaction Rolled Back)

Begin transaction

If all goes well, commit transaction

If problem occurs,Abort transaction

Final State(Transaction Succeeded)

Initial State(No Transaction Occurring)

Perform one or more smaller-grained transactions

Page 27: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

53

EJB Transaction AttributeEJB Transaction AttributeBean Managed Transaction

TX_BEAN_MANAGED

Container Managed TransactionTX_NOT_SUPPORTEDTX_REQUIREDTX_REQUIRES_NEWTX_SUPPORTSTX_MANDATORYTX_NEVER

EJB Key Concept

©200

0 S

oo D

ong

Kim

54

bean

Thread of execution Client’s transactional context

Bean’s transaction context No transactional context

Client(bean or app) TX_REQUIRED

Client(bean or app) TX_REQUIRED

Container Managed TransactionContainer Managed TransactionTX_REQUIRED

bean

Page 28: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

55

Thread of execution Client’s transactional context

Bean’s transaction context No transactional context

Client(bean or app) TX_REQUIRES_NEW

Client(bean or app) TX_REQUIRES_NEW

Container Managed TransactionContainer Managed TransactionTX_REQUIRS_NEW

bean

bean

EJB Key Concept

©200

0 S

oo D

ong

Kim

56

Transactional IsolationTransactional IsolationFour transaction Isolation levels in EJB

TRANSACTION_READ_UNCOMMITTEDNot offer any isolation guarantees.But offers the highest performance.

TRANSACTION_READ_COMMITTEDSolves the dirty read problem.

TRANSACTION_REPEATABLE_READSolves the previous problems as well as the unrepeatable read problem.

TRANSACTION_SERIALIZABLESolves the previous problems as well as the phantom problem.

Page 29: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

57

TwoTwo--Phase CommitPhase CommitThe Two phase commit protocol

The two-phase commit protocol is useful Allows for many transaction managers and resource managers to participate in a transaction across a deployment.If any participant votes that the transaction should abort, all participants must roll back.

EJB Key Concept

©200

0 S

oo D

ong

Kim

58

TwoTwo--Phase CommitPhase Commit

TransactionCoordinator

TransactionManager

TransactionManager

TransactionManager

Resource manager

Resource manager

Transaction Participants

1:prepare to commit

2:return

4:commit

5:return

3:log result

The commit operation islogged in case of a crash.

Page 30: EJB Key Concept

EJB Key Concept

©200

0 S

oo D

ong

Kim

59

-- End End --