Unit 7: Enterprise Java Beans EJBs - PowerPoint PPT Presentation

1 / 112
About This Presentation
Title:

Unit 7: Enterprise Java Beans EJBs

Description:

Beans are expected to be deployed in many ... Builds applications using beans, including the presentation layer ... Provides run-time services to support beans ... – PowerPoint PPT presentation

Number of Views:460
Avg rating:3.0/5.0
Slides: 113
Provided by: loisemi
Category:
Tags: beans | ejbs | enterprise | java | unit

less

Transcript and Presenter's Notes

Title: Unit 7: Enterprise Java Beans EJBs


1
Unit 7 Enterprise Java Beans - EJBs
  • Building J2EE Applications in SilverStream

Instructor Notes To make the instructor notes
invisible in this unit, select ViewComments.
2
Section Objective
  • Describing Enterprise JavaBeans
  • Understanding EJB basics
  • Calling EJBs
  • Session beans
  • Entity beans
  • Using transactions
  • Adding security

3
EJBs in the SilverStreameBusiness Platform
Tools
Components
Components
3rd PartyComponents
CustomComponents
Portal Component Framework
eBusiness Services
ContentManagement
Web Publishing
Personalization
Rules Engine
ContentCaching
Workflow
User Profiling
XML Integration
J2EE Application Server
Presentation
Business Logic
Transactions
Messaging
Scalability
Reliability
Security
Management
Enterprise Connectivity
4
Enterprise JavaBean Characteristics
  • A reusable software component that is remotely
    accessible, transactional, secure.
  • Easy to replace
  • Contains all its needed logic
  • Can be provided by third partiesExample credit
    card verification object
  • Deployed in a container that
  • Handles remote access, transactions, security
  • Makes the bean accessible to clients

Instructor Notes Enterprise JavaBeans are very
different from JavaBeans. JavaBeans run on the
client, whereas EJBs run on the server. They
have very different specifications. However,
they both have the goal of making components
reusable.
5
Distributed Computing
  • Application may need to access data from
  • Legacy systems.
  • Remote locations.
  • Distributing computing
  • Allows client to access remote data as if local.
  • Needs to be platform independent.
  • Requires industry standards. CORBA is one
    example. EJB is the standard in J2EE.

Instructor Notes In the past, other environments
have tried to address distributed computing.
With EJBs, you can think of this concept being
moved into the Java environment. Containers are
new with the Java implementation.
6
Distributed Computing Basics
Instructor Notes Distributed computing is not
new. The stub might also be called a proxy or
surrogate. The tie might also be called a
skeleton. Tie is more technically accurate, but
many people are familiar with the term skeleton.
Client
Server
Stub
Tie
Object
Stub defers method calls to tie.
1. Client calls business method on stub as if it
were the real object.2. Stub communicates
request to tie.3. Tie calls method on real
object.4. Result is returned back.
7
Distributed Computing with EJBs
Client
Server
Stub
Tie
Home interface
EJBHome Object
Stub
Tie
Remote interface
EJB Object
In EJBs, you also need a stub for a home object
in order to create, find, and remove the bean
object.
Instructor Notes You may want to spend extra time
explaining the home and remote interfaces.
8
The Benefits of Enterprise JavaBeans
  • Simplified coding
  • Business logic only
  • Container provides access to services
  • Standards-based portability
  • Separate configuration
  • Beans are expected to be deployed in many
    different environments, so configuration
    information is declarative.
  • Role-oriented design

Instructor Notes The declarative information is
contained in a deployment descriptor file. Much
of what the bean writer writes is not in the code
but in the deployment descriptor. This makes it
more flexible.
9
When Should I Use EJBs?
  • When it is important to build reusable components
  • Division of labor is beneficial
  • Ease of maintenance is desired
  • Your company chooses it as the standard for
    distributed computing
  • You want to use third party solutions
  • You are building applications for vertical markets

Instructor Notes Use EJBs for the business logic
and data access portion of a J2EE application.
10
EJB Development Roles
Main development roles
BeanWriter
BeanDeployer
ApplicationAssembler
EJB container/serverprovider
11
Bean Writer Role
Main development roles
BeanWriter
BeanDeployer
ApplicationAssembler
EJB container/serverprovider
  • Writes bean code for re-use by others
  • Provides interfaces and implementation
  • Has little concern about transactions, threads,
    security, state, remote protocols, (optionally)
    persistence
  • Makes very generic references to data and
    security access
  • May use any available Java tools
  • Could be a third-party vendor

12
Application Assembler Role
Main development roles
BeanWriter
BeanDeployer
ApplicationAssembler
EJB container/serverprovider
  • Builds applications using beans, including the
    presentation layer
  • May specify transaction management
  • May use any available Java tools
  • Same person might also be a bean writer for
    internally developed beans

13
Bean Deployer Role
Main development roles
BeanWriter
BeanDeployer
ApplicationAssembler
EJB container/serverprovider
  • Maps fields to actual database columns
    (persistence)
  • Maps roles to user/group names (security)
  • Uses deployment tools to create wrapper classes

Instructor Notes The Deployment Plan Designer was
new in 3.5. You create a plan which can then be
deployed.
14
Container/Server Role
BeanWriter
BeanDeployer
ApplicationAssembler
EJB container/serverprovider
  • Provides deployment tools
  • Generates code to handle transactions, security,
    state, remote protocols, and persistence based on
    deployment descriptor
  • Provides run-time services to support beans

15
What the Container Provides
  • Tools for customizing and deploying beans
  • Utility classes to provide server information
  • Generated classes that implement certain features
    of the bean. Generated classes handle
  • Transaction and security issues.
  • Pass-through and business logic methods to the
    bean.
  • Loading and storing the beans persistent data.
  • Generated remote stubs for the wrappers (RMI,
    CORBA, or other).

16
EJB Lifecycle
Instructor Notes This slide is animated to show
what happens when you make a remote call to an
EJB. The server handles all details of security
and transactions. With EJBs, the calls go
through many interfaces. Even calls from one
bean to another bean go through interfaces.
Server
Client
JNDI
Name
Home interface
Container
Bean class
Remote interface
SessionContext
Bean writer provides
17
EJBs in SilverStream
  • SilverStream provides a CORBA-based fully
    integrated solution compliant with EJB 1.1.
  • EJBs are accessible from JSPs, servlets,
    SilverStream pages/forms/business objects, and
    external clients.
  • EJBs can access objects running on other servers.
  • The entire application could reside on a
    SilverStream server.
  • You have full interoperability with CORBA clients
    and servers.

Instructor Notes In the SilverStream Application
Server, the EJB solution is provided in CORBA
through JBroker.
18
SilverStream EJB Support
  • Client access
  • HTML clients (JSPs, servlets, SilverStream pages)
  • Java clients (external Java applications,
    SilverStream forms)
  • Tool integration
  • SilverStream provides a robust set of development
    tools.
  • EJB classes can be written using any third-party
    IDE and imported into the SilverStream server.
  • Integrates with Inline and JBuilder

Instructor Notes New in 3.7, an EJB Create Wizard
makes it easy to generate the relevant classes
when writing a bean. With external Java clients,
you must compile with the JBroker JAR files.
19
SilverStream EJB Support (2)
  • Complete EJB implementation including
  • Stateless and stateful session beans
  • Entity beans with CMP or BMP
  • Remote access via RMI-IIOP
  • Integration with SilverStream security and load
    balancing
  • Full support for creating, customizing,
    deploying, and administering EJBs

20
Section Objective
  • Describing Enterprise JavaBeans
  • Understanding EJB basics
  • Calling EJBs
  • Session beans
  • Entity beans
  • Using transactions
  • Adding security

21
Two Types of Beans
  • Session beans
  • Use for logic and data of a transient nature.
  • Entity beans
  • Use for persistent data.

22
Session Beans
  • Session beans
  • Implement javax.ejb.SessionBean
  • Think of as verbsExample A bean that
    calculates tax rates
  • Can be stateful or stateless
  • Stateful. State maintained throughout the
    session.
  • Stateless. State not retained.

Instructor Notes New in 3.7, session beans can be
pooled. This is specified at deployment.
23
Example of a Session Bean
  • Shopping Cart Bean
  • Keeps track of customers choice while shopping
  • Provides actions associated with putting items in
    the virtual shopping cart
  • Methods include addItem(), getItem(), and
    calcGrandTotal().
  • Interacts with entity beans that store the items.
  • See
  • silverbooks\src\components\shoppingcart\src\com\ss
    sw\demo\silverbooks\ejb\ sessionbeans\ShoppingCa
    rt.java

24
Entity Beans
  • Entity beans
  • Implement javax.ejb.EntityBean
  • Think of as nounsExample A customer record
  • Has a primary key to uniquely identify record.
    Finder methods for queryingfindByPrimaryKey()
    returns a unique bean.findXXX() methods return
    Collections of beans.

25
Example of an Entity Bean
  • Book Bean
  • Holds information about each book
  • Contains fields such as title, author ID, unit
    price, description
  • Methods usually involve getting and setting data,
    such as setTitle(), setDescHTML(), and
    getBookID()
  • See
  • silverbooks\src\components\beans\src\com\sssw\dem
    o\silverbooks\BookBean.java

26
Accessing Entity Beans
  • Encapsulating access is a good idea because
  • Do not want to start a transaction from a remote
    (Java) client
  • Do not want to expose entity beans directly to
    remote Java clients
  • Allows for reusable code
  • Managing entity bean transactions via a session
    bean
  • Can use declarative transaction management
  • Does not depend on correctness of client
    application

27
To Encapsulate or Not?
EJBclient 1
Customer
Order
EJBclient 2
OrderItem
Customer
EJBclient 1
Encap-sulatingsession bean
Order
EJBclient 2
OrderItem
28
Calling an EJB from Another EJB
  • To encapsulate an entity bean with a session
    bean, you need a reference.
  • EJB specification provides a simple way to access
    other bean homes bean references.
  • You specify bean references in the deployment
    descriptor.
  • The bean writer does not have to know the JNDI
    name of the bean class.
  • The writer can define multiple homes for a single
    class to allow the same bean class to be deployed
    with different names.

29
EJB Class Naming Conventions
  • EJB classes typically use a naming convention to
    identify the interface type.
  • Home as suffix for home interfaces
  • Bean as suffix for bean classes
  • You may also see conventions for the bean type.
  • For example, SB or EB in the name
  • Beans of the same type usually put together in
    same subpackage

30
Packaging EJBs
  • EJBs are packaged in the same process as web
    components.
  • Bean writer places them in an EJB JAR file.
  • Has a .jar extension
  • Contains the EJB Java class files plus the home
    and remote interfaces
  • EJB JAR also contains a deployment descriptor in
    XML.
  • Named ejb-jar.xml (similar to web.xml)
  • Needs to be located in META-INF

31
EJB JAR File Contents
  • Contains EJBs and their related classes.
  • Example
  • META-INF\
  • ejb-jar.xml
  • myPackage\
  • MyLogic.class
  • MyLogicHome.class
  • MyLogicBean.class

Deploymentinformation
32
EJB Deployment Information
  • Has many of the same entries as web components
  • Environment entries
  • Bean references
  • Resource references

33
Deploying EJB Components
  • Deploying EJB components is also the same process
    as with web components
  • Deployer creates a deployment plan based on the
    EJB JAR
  • Based on deploy_ejb.dtd
  • Use SilverCmd to deploy the EJB JAR into the
    server

Instructor Notes When using SilverCmd, you must
supply the XML file.
34
What Happens at Deployment
  • When you call DeployEJB
  • SilverStream generates the following classes-
    EJBObject- EJBHome- Stub/tie classes
  • SilverStream generates the following objects
  • xxxDeployed (file used by server)
  • xxxRemote.jar (file used by client)
  • Includes the original classes plus generated
    classes.

35
EJB Deployment Plan
  • Basic EJB deployment plan


source.jar
true
remote.jar
deployed.jar
some.jar
continues bj_ejbJarOptions
36
EJB Deployment Plan (2)
  • Declaring beans
  • Starts under

session bean
specifics entity
bean specifics
37
EJB Deployment Plan (3)
  • Many of the options available for web components
    are available for EJB components
  • Environment list
  • Bean reference list
  • Resource reference list
  • Role map

38
Sample EJB Deployment Plan
standalone"yes"?
truesEnabled myejb.jar
myejbRemote

39
Sample EJB Deployment Plan (2)

MySessionBeanName ejb/jndinameDIName

mydatasource
javax.sql.DataSource




40
Sample EJB Deployment Plan (3)

myfirstrole
Administrators


41
SilverCmd ValidateEJB
  • SilverCmd ValidateEJB ejbJarFile options
  • Validates the deployment descriptor within
    specified EJB JAR file and reports problems.
  • Use when building EJB JAR and descriptor outside
    of SilverStream IDE, to verify before importing.
  • Example SilverCmd ValidateEJB JDBCSource.jar

42
SilverCmd DeployEJB
  • SilverCmd DeployEJB serverport
    databaseejbJarFile -d ejbDeployedObject-r
    ejbRemoteJar -f deploymentPlan-R
    remoteJarPath options
  • Deploys EJB JAR on named SilverStream server.
  • Use to deploy an EJB JAR that was authored
    outside of SilverStream IDE.
  • ExampleSilverCmd DeployEJB localhost
    SilverBooksBegin -f JDBCSourceDeplPlan.xml

43
SilverCmd QuickDeployEJB
  • SilverCmd QuickDeployEJB serverport database-j
    ejbJarFile -d ejbDeployedObject-r
    ejbRemoteJar -f deploymentPlan-s
    rootdirectory -R remoteJarPath options
  • Compiles and deploys EJB components that changed
    since last full deployment.
  • Use during development for small iterative
    changes to EJBs.
  • ExampleSilverCmd QuickDeployEJB
    localhost SilverBooksBegin -f JDBCSourceDeplPlan.
    xml

44
Section Objective
  • Describing Enterprise JavaBeans
  • Understanding EJB basics
  • Calling EJBs
  • Session beans
  • Entity beans
  • Using transactions
  • Adding security

45
Calling EJBs
  • EJBs deployed on the SilverStream Server can be
    called from
  • JSPs
  • Servlets
  • Other EJBs
  • External Java applications
  • Java forms (SilverJRunner)
  • SilverStream pages
  • SilverStream triggered business objects

46
Steps for Calling EJBs
  • To call an EJB
  • 1. Find the EJBHome (using JNDI).
  • 2. Use the EJBHome to create an instance.
  • 3. Call the business methods on the EJBObject.
  • 4. Remove the bean when done.

47
1. Finding the EJBHome
  • Create an InitialContext.
  • Look up object by its JNDI name.
  • Narrow it to the right type.

javax.naming.InitialContext initialContext
new javax.naming.InitialContext()
Object obj initialContext.lookup (RMI/EJBCourse
End/ejbcourse/runningtotal/
sessionbeans/SBRunningTotal")
SBRunningTotalHome sbRunningTotalHome
(SBRunningTotalHome) javax.rmi.PortableRemoteObje
ct.narrow(obj, ejbcourse.runningtotal.sessionbean
s.SBRunningTotalHome.class)
Instructor Notes A context is like a directory
you look up a name a get back a value. You must
cast to get the home interface. But in CORBA you
get a remote reference. CORBA has to check that
it is the right type. Always use narrow then a
cast when you need to cast a remote object. This
is a CORBA restriction. It is safe to use narrow
on any reference.
48
2. Creating an Instance
  • Create an instance.

SBRunningTotal sbRunningTotal
sbRunningTotalHome.create()
49
3. Calling Business Methods
  • Once your client has a remote reference to the
    EJB
  • You can call any of the exposed business methods
    (on the EJBObject) and the lifecycle methods (on
    the EJBHome) as though the EJB were local.
  • The bean writer must provide some type of
    documentation that describes the EJB's available
    business methods.

50
Code Example Calling from JSP
  • Sample samplenull
  • try
  • ic new InitialContext()
  • Object obj ic.lookup(RMI/SilverBooks/Sample)
  • SampleHome sampleHome (SampleHome)
  • javax.rmi.PortableRemoteObject.narrow(obj,
  • com.sssw.demo.silverbooks.ejb.sb.SampleHome.cl
    ass)
  • sample (Sample) sampleHome.create()
  • catch (Exception e)...
  • finally ... // close context if not null
  • The data is

51
Section Objective
  • Describing Enterprise JavaBeans
  • Understanding EJB basics
  • Calling EJBs
  • Session beans
  • Entity beans
  • Using transactions
  • Adding security

52
Session Beans
  • Two types of session beans
  • Stateful
  • Stateless
  • Used to implement server-side business logic
  • Session beans can
  • Access data (AgaDatas or directly with JDBC).
  • Participate in distributed transactions.
  • Invoke other beans.

Instructor Notes Session beans are not shared
among multiple clients. They run as part of the
clients session. With stateful beans, the
server saves information on the clients behalf.
With stateless beans, the EJB specification
allows vendors to call any bean so that fewer
beans are needed, but currently the SilverStream
Application Server does not pool stateless beans.
This may change in the future. It is a vendor
optimization that does not affect the bean writer.
53
Session Bean Class
  • Write a Java class that
  • Extends from any base class.
  • Implements javax.ejb.SessionBean.
  • Includes one or more ejbCreate() methods.
  • Includes business methods.

Instructor Notes When the session times out,
beans are cleaned up immediately.
54
Defining an ejbCreate() Method
  • Required by the EJB specification
  • Sometimes used to initialize the bean

public void ejbCreate() throws javax.ejb.CreateExc
eption, java.rmi.RemoteException
Instructor Notes If the exception is thrown, the
bean is not created. You can have overloaded
ejbCreate() methods with various parameters. You
must have at least one version of the method. An
example of what you might do in this method is
open a TCP connection.
55
Writing Business Methods
  • Define methods like any other method.
  • You must add any of the beans business methods
    to the beans remote interface.

public int addToTotal(int piNumber)
m_iTotal piNumber return m_iTotal
Instructor Notes This is the real work of the
bean.
56
Creating a Remote Interface
  • Write a remote interface that
  • Extends javax.ejb.EJBObject.
  • Includes every business method on the bean that
    you want to expose to the beans clients.
  • The bean class should not implement the remote
    interface.

Instructor Notes It is best to write the remote
interface before the home interface to avoid a
compile error. By extending javax.ejb.EJBObject,
you tell the SilverStream Application Server that
this is a remote interface. Another approach is
to paste in methods and remove the code in the
body. It is allowable to have extra methods in
the code, but they are useless outside of the
interface.
57
Methods in Remote Interfaces
  • All business methods declared in the remote
    interface
  • Must have same parameters and same return value
    type.
  • Contain a superset of the beans exceptions.
  • Methods in the remote interface must also throw
    java.rmi.RemoteException.
  • Not all of the beans methods have to be exposed
    to remote clients.

Instructor Notes The bean cannot throw any other
type of exception that the client does not know
about. You may want to discuss RMI here. EJBs
are built on top of the RMI packages. Notice
that the remote interface EJBObject extends
java.rmi.Remote. So it must follow all of the
RMI rules, such as throwing RemoteException.
58
Creating a Home Interface
  • Write a home interface that
  • Extends javax.ejb.EJBHome.
  • Includes a create() method for every
    corresponding ejbCreate() method on the bean.

Instructor Notes This is the factory. The
create() and ejbCreate() methods have different
result types, so they have different names. They
are otherwise identical. You cannot add your own
methods in EJB 1.1. This may be relaxed in EJB
2.0.
59
More About the create() Methods
  • The create() methods return remote references.
  • Value returned to client after bean and EJBObject
    instances created and initialized
  • Return value is reference to newly created
    EJBObject
  • The create() methods must be able to throw
    additional exceptions.
  • java.rmi.RemoteException to indicate system
    exception
  • javax.ejb.CreateException if object not created

60
Packaging EJBs
  • How do you package EJBs so they can be deployed
    or assembled into an application?
  • Place them in an EJB JAR file that includes
  • One or more EJB Java class files.
  • The home and remote interfaces for the EJBs.
  • A deployment descriptor.

Instructor Notes Unlike business objects, EJBs
must be put in a JAR to be used. The JAR must
also include any helper classes, plus the
deployment descriptor. Mention particularly the
deployment descriptor since it is such an
important part of EJBs. In the JAR Designer, it
may appear that you can include other JAR files.
What happens is that the JAR Designer copies the
JAR contents from another JAR.
61
Packaging EJBs (2)
  • Create an EJB JAR.
  • Add the classes to be included in the JAR.
  • Provide an XML deployment descriptor that
    contains structural information about the EJB
    including- Java class file, remote interface,
    home interface- State management type,
    transaction management type
  • Optional (but normally)- Define one or more
    role names, environment entries, and datasource
    references.

Instructor Notes The deployment descriptor is the
important piece. There is one deployment
descriptor for the JAR. You could even write it
with a text editor. In EJB 1.1, XML is used.
EJB 1.0 used a serialized class.
62
Deploying EJBs
  • Choose the EJB JAR you want to deploy and
  • Right-click and select Create EJB JAR Deployment
    Plan.
  • From Deployment Plan Designer, select FileSave
    and Deploy.
  • As an alternative, you can run SilverCmd
    DeployEJB, passing the appropriate parameters.

Instructor Notes When using SilverCmd, you must
write the XML file.
63
What Happens at Deployment
  • When you DeployEJB
  • SilverStream generates the following classes-
    EJBObject- EJBHome- Stub/tie classes
  • SilverStream generates the following objects
  • xxxDeployed (file used by server)
  • xxxRemote.jar (file used by client)
  • Includes the original classes plus generated
    classes.

64
Deploying Session Beans
  • Defines one or more create() methods
  • Extends EJBHome
  • getEJBMetaData()
  • remove(Handle h)
  • remove(Object primaryKey)
  • Must follow RMI rules

Server
JNDI
Name
EJB JAR file
Container
Home
Remote
Bean class
Bean class
Deployment Descriptor
Environment properties
  • Extends EJBObject
  • getEJBHome()
  • getHandle()
  • getPrimaryKey()
  • isIdentical()
  • remove()
  • Must be a valid RMI/IDL value

Instructor Notes This slide is animated. Notice
that there are many places for failure.
65
Using Deployed JARs
  • You can publish any EJB JAR to other SilverStream
    servers.
  • You must then deploy the EJB on the target
    server.
  • If Enabled property is set to true, the deployed
    EJB JAR is activated when installed.
  • Use SMC to enable/disable a deployed EJB JAR.

66
Exercise 7-1 Create, Deploy, and Call a
Session Bean
Instructor Notes Demonstrate the exercise for the
students before they begin. Familiarize the
students with the course database. Point out that
the Instructions section gives general steps,
while the Guided Instructions section gives
detailed steps. Students should choose one
section to work from, but not both.
67
Section Objective
  • Describing Enterprise JavaBeans
  • Understanding EJB basics
  • Calling EJBs
  • Session beans
  • Entity beans
  • Using transactions
  • Adding security

68
What are Entity Beans?
  • They represent persistent underlying objects
  • A row in a relational database
  • Data in flat files
  • Data in some data stream
  • Each entity bean is uniquely identified by a
    primary key.
  • Home interface for entity beans includes Finder
    methods for querying
  • findByPrimaryKey() returns a unique bean
  • findXXX() methods return Collections of beans
    (object-based query methods)

69
Entity Beans
PrimaryKey
Field2
Remote calls
Field3
Business logic
Instructor Notes This slide is animated.
70
Who Manages Persistence?
  • Persistence defines
  • Who finds stored data.
  • Who constructs an entity bean for each record.
  • Who updates each record when the corresponding
    entity bean is modified.
  • If the container does this, it is called
    container-managed persistence (CMP).
  • If the bean writer does this, it is called
    bean-managed persistence (BMP).

71
Understanding BMP
  • The bean writer codes all methods that access the
    database.
  • This includes coding to
  • JDBC API
  • Transactions
  • Binding
  • PreparedStatements
  • and so on...

Instructor Notes BMP provides the ultimate in
flexibility. It is best to design the bean not
for BMP, but for CMP. Then if you need to have
BMP, subclass the bean and but the BMP code in
the subclass. This makes it easy to move to a
new server that handles CMP in the way that you
need. It also allows you to write subclasses for
various databases.
72
Understanding CMP
  • The container generates all of the hard to
    write code.
  • The bean writer
  • Declares CMP in the deployment descriptor.
  • Declares the member variables that the container
    should get and set.
  • The deployer
  • Maps the member variables to the appropriate
    database columns.
  • Maps finder methods to SilverStream expressions.

Instructor Notes In the SilverStream Application
Server, using CMP is similar to using agData.
73
BMP Pros and Cons
Instructor Notes The tradeoffs between CMP and
BMP are similar to the tradeoffs between AgxDatas
and DSOs. BMP usually means database-dependent
code. CMP gives you what you get with agData.
In 3.0, you cannot have CMP for DSOs you must
use BMP with DSOs.
  • Pros
  • Container-independent- Standards-based simple
    EJB API and JDBC- Allows access to non-standard
    data
  • Flexible- Supports algorithms of any complexity
  • Cons
  • Database-dependent- Bean code is
    database-specific including table and field
    names- Uses features specific to a database-
    Bean writer must know SQL

74
CMP Pros and Cons
  • Pros
  • Easier to write and maintain
  • Database-independent- Bean writer does not have
    to write database access code- Allows bean
    writer to use containers value-added features
    (such as full-text search)
  • Cons
  • Allows only container-supported algorithms for
    persistence (such as, what can be specified in
    declarations)

Instructor Notes The two main methods in BMP are
ejbStore() and ejbLoad().
75
BMP ejbStore()
  • What a BMP ejbStore() method looks like

Connection connection getConnection()
PreparedStatement preparedStatement null try
preparedStatement connection.prepareStatement(
UPDATE_ACCOUNT) preparedStatement.setInt(1,
m_account_type.intValue()) preparedStatement.set
Int(2, m_customer_id.intValue())
preparedStatement.setDate(3, m_date_opened)
preparedStatement.setBigDecimal(4,
m_current_balance) preparedStatement.setString(5
, m_account_number) preparedStatement.executeUpd
ate() catch (SQLException x) ... throw
new EJBException finally ...
Instructor Notes Real-life code is even more
complex.
76
CMP ejbStore()
  • What a CMP ejbStore() method looks like

public void ejbStore() throws java.rmi.RemoteExcep
tion
Instructor Notes This code looks a lot simpler
than BMP!
77
Developing Entity Beans
  • Writing the primary key class (if needed)
  • Writing the bean class
  • Writing the home and remote interfaces

Instructor Notes Writing entity beans is similar
to writing session beans, except you must write a
primary key class, if needed, and finder
methods. You need to think about transactions
when developing entity beans, because each call
to an entity bean may re-get the information and
then throw it away. A couple approaches to
minimize this are 1. Start the transaction,
read in the info, perform functions, then
commit. 2. Use a session bean to manage the
transaction and be the front for the entity bean.
This keeps you from having to write transaction
management code, and allows the container to
handle transactions more expertly. Set the
session bean to use an existing transaction if
there is one, else start a new one.
78
Creating a Primary Key Class
  • Write a Java class that
  • Extends from any base class.
  • Implements java.io.Serializable.
  • Includes an implementation of equals() and
    hashCode() methods.
  • For simple keys, you do not need to write a
    primary key class.

79
The hashCode() Method
  • Required by the EJB 1.1 specification so the
    container can determine if bean instances are the
    same

public int hashCode() return
m_stateID.hashCode()
80
The equals() Method
  • Required by the EJB 1.1 specification so the
    container can determine if bean instances are the
    same

public boolean equals(Object objPK) if
(objPK instanceof EBStatePrimaryKey) return
m_stateID.equals( ((EBStatePrimaryKey)
objPK).m_stateID) return false
81
Creating an Entity Bean Class
  • Write a Java class that
  • Implements javax.ejb.EntityBean
  • Extends from any base class
  • Includes member variables representing database
    fields that you want to use

82
Defining the Member Variables
  • An entity bean includes a member variable for
    each database field you want the bean to
    manipulate.
  • Define them in the GeneralDeclarations section.
  • For CMP, member variables must be public.

public String m_StateID public String
m_stateName public BigDecimal m_taxRate
83
Defining an ejbCreate() Method
public EBStatePrimaryKey ejbCreate(String
psStateID, String psStateName, BigDecimal
pdbTaxRate) throws StateSalesTaxException, Cre
ateException, RemoteException m_stateI
D psStateID m_stateName psStateName m_ta
xRate pdbTaxRate return null
Instructor Notes Make sure the students
understand the difference between session beans
and entity beans when using create() and
remove(). For session beans, these methods
create and remove instances of the bean. For
entity beans, these methods create and remove
actual database records!
84
Defining ejbPostCreate() Method
  • A method on the javax.ejb.EntityBean interface
  • Implementation required by EJB 1.1 specification
  • Lets you do data manipulation after the bean is
    created, but before the client gets it

public void ejbPostCreate(String psStateID,
String psStateName, BigDecimal pdbTaxRate)
throws StateSalesTaxException,
CreateException, RemoteException
85
Writing Business Methods
  • An entity beans business methods generally
    manipulate data (get or set) or apply business
    logic to data.

public String getStateName() throws
RemoteException return m_stateName
public void setStateName(String psStateName)
throws RemoteException m_stateName
psStateName return
86
Creating a Remote Interface
  • Write a remote interface that
  • Extends javax.ejb.EJBObject.
  • Includes the data manipulation methods that you
    want to expose to the beans clients.

87
Methods in Remote Interfaces
  • Like session bean business methods, all business
    methods are declared in the remote interface.
    They
  • Must have same parameters and same return value
    type as the entity bean.
  • Can differ in exceptions thrown.
  • Must also throw java.rmi.RemoteException.

88
Creating a Home Interface
  • Write a home interface that
  • Extends javax.ejb.EJBHome.
  • Includes a create() method for every
    corresponding ejbCreate() method on the bean.
  • Includes finder method declarations.
  • At deployment, the container constructs an
    EJBObject from this interface.

89
Writing Finder Methods
  • Finders are like SQL Select statements.
  • Finders must throw FinderException.
  • Finder methods can return one or more beans.

90
More About Finder Methods
  • Finders depend on the persistence model.
  • In BMP
  • You write the ejbFindxxx() method.
  • In CMP
  • The finder method is mapped to a SilverStream
    expression at deployment.
  • For very complex finders, you can write the
    method implementation.

91
Packaging Entity Beans
  • Create an EJB JAR
  • Add the classes to be included in the JAR.
  • Provide an XML deployment descriptor that
    contains structural information about the bean,
    including- Java class file, remote interface,
    home interface, primary key class.- Transaction
    management type, persistent fields.
  • Optionally (but normally)- Define role names,
    environment entries, datasource references, and
    role references.

92
Deploying Entity Beans
  • Choose the EJB JAR you want to deploy and
  • Right-click and select Create EJB JAR Deployment
    Plan.
  • From Deployment Plan Designer, select FileSave
    and Deploy.
  • Or, run SilverCmd DeployEJB, passing the
    appropriate parameters.

93
Deploying Entity Beans
Server
  • Extends EJBHome
  • getEJBMetaData()
  • remove(Handle h)
  • remove(Object primaryKey)
  • Must follow RMI rules
  • Defines zero or more create() methods

JNDI
Name
EJB JAR file
Container
Home
Remote
Bean class
Bean class
Deployment Descriptor
Environment properties
  • Extends EJBObject
  • getEJBHome()
  • getHandle()
  • getPrimaryKey()
  • isIdentical()
  • remove()
  • Must be a valid RMI/IDL value

Primary key
Instructor Notes This slide is animated.
94
Creating and Calling Entity Beans
Server
Client
JNDI
getEJBObject() getPrimaryKey() getEJBHome() getEnv
ironment() getCallerIdentity() isCallerInRole() se
tRollbackOnly() getRollbackOnly() getUserTransacti
on()
Name
Home interface
Container
Bean class
EntityContext
Remote interface
Instructor Notes This slide is animated.
95
Finding and Calling Entity Beans
Server
Client
JNDI
Name
Home interface
Container
Bean class
EntityContext
Remote interface
Instructor Notes This slide is animated.
96
Exercise 7-2 Create an Entity Bean and Modify
the SB to use it
Instructor Notes Demonstrate the exercise for the
students before they begin. Note In some
places, the course databases show the Bean class
declaring that it throws RemoteException. This
is not really necessary, but does not hurt. It
is automatically generated by the wizard. Only
the remote interface needs to declare that it
throws RemoteException.
97
Section Objective
  • Describing Enterprise JavaBeans
  • Understanding EJB basics
  • Calling EJBs
  • Session beans
  • Entity beans
  • Using transactions
  • Adding security

98
Transaction
  • Defined as one or more tasks that execute as a
    single atomic operation
  • Guarantees an all or nothing proposition
  • Referred to as a unit of work
  • Characterized by four properties (ACID)
  • Atomic
  • Consistent
  • Isolated
  • Durable

99
Three Fundamental Operations of a Transaction
  • Start transaction
  • Commit transaction
  • Updates resources to include changes made since
    the transaction started
  • Rollback transaction
  • Cancels all of the changes made since the
    transaction started

100
Transaction Example Money Transfer
Before transaction
After transaction
Unit ofwork
Commit
Checking 25 Savings 125
Transfer money Withdraw 75 from checking Deposit
75 to savings
Checking 100 Savings 50
Checking 100 Savings 50
Rollback
101
Transaction Participants
  • Application server
  • Assists in managing transactional resources used
    by beans
  • Transaction manager
  • Controls state of transaction
  • Coordinates all resource managers within
    transaction
  • Resource manager
  • Does actual commit or rollback
  • JDBC driver
  • Resource
  • Persistent storage
  • Database
  • Transactional component
  • Can control transaction via interface to
    transaction manager
  • EJB or client

102
Support for Transactions
  • Flat transactions
  • Nested transactions are not supported in EJB
    specification.
  • Single-phase commit protocol
  • Only one resource manager can participate in a
    transaction.
  • Support for two-phase commit protocol may be
    supported in an upcoming SilverStream Application
    Server release.

Instructor Notes XA-compliant JDBC drivers
support two-phase commits, but none of them are
drivers that SilverStream supports.
103
Who Manages EJB Transactions?
  • Container-managed transaction (CMT)
  • Transactions demarcated by the container
  • Based on transaction attributes specified in the
    deployment descriptor
  • Bean-managed transaction (BMT)
  • Transactions demarcated programmatically
  • Based on code in the business methods
  • Bean writer must decide between CMT or BMT

Instructor Notes Students should be careful not
to confuse CMT with CMP or BMT with
BMP. Demarcation defines who starts and ends the
transaction.
104
Transaction Attributes
  • NotSupported. Runs without transaction.
  • Supports. Use existing transaction.
  • Required. Must have transaction.
  • RequiresNew. Always starts new transaction.
  • Mandatory. Transaction must already exist.
  • Never. Must never run with transaction.

105
Section Objective
  • Describing Enterprise JavaBeans
  • Understanding EJB basics
  • Calling EJBs
  • Session beans
  • Entity beans
  • Using transactions
  • Adding security

106
Security Aspects Not Coveredby EJB Specification
  • Authentication not in spec
  • Who is the user?
  • Already handled by the SilverStream Application
    Server via users and groups, and other security
    domains.
  • Secure communication not in spec
  • Was the transmission correct?
  • Already handled with HTTPS.

107
Security in EJB Specification
  • Access control
  • What can the user do?
  • Some decisions delayed until deployment
  • Bean writer, application assembler, and bean
    deployer add various security information
  • Can be declarative (container-managed) or
    programmatic (bean-managed)
  • Need to provide way for user to log in

Instructor Notes The EJB 1.1 specification is
based on java.security.Principal and is
role-driven. The security identity is passed
along to other beans. Another security feature is
using the SilverStream Management Console (SMC)
to set row-level security on database tables. New
in 3.7, beans can use SSL to communicate. This
is a checkbox at deployment.
108
Declarative Access Control
  • If just controlling access at the method level,
    bean writer does not need to code for security.
  • Bean writer need not do anything.
  • It is helpful to add descriptive text.
  • Application assembler will add roles and
    associate them with methods.

109
Application Assembler
  • Defines security roles. Example
    AccountingGroup
  • Associates roles with methods by adding
    permissions.
  • Can specify particular methods.
  • Use wildcard to apply to all methods.

110
Bean Deployer
  • Looks at the roles set up by the application
    assembler
  • Maps roles to real users and groups in the
    deployment environment
  • Deployer does not worry about method permissions.
  • Textual descriptions of roles should be enough to
    decide on mappings.

111
Role References
  • Bean writer can also programmatically use a
    generic security reference. Example
    Accounting
  • Bean writer must then specify a role reference in
    the EJB JAR.
  • In the SilverStream JAR Designer, right-click
    Environment and select Add Role Reference.
  • Specify its properties.

112
Review Questions
  • What does distributed computing allow the client
    to do?
  • What are the roles involved in developing EJBs?
  • When would you use a session bean? An entity
    bean?
  • What are the tradeoffs between CMP and BMP?
  • What are the steps to call an EJB from a client?
Write a Comment
User Comments (0)
About PowerShow.com