EJB Design Patterns - PowerPoint PPT Presentation

1 / 82
About This Presentation
Title:

EJB Design Patterns

Description:

Provides a high-level language to discuss design issues. ... Commands can become unmanageable on large. projects. EJB Design Pattern (c) CDAC(Formerly NCST) ... – PowerPoint PPT presentation

Number of Views:204
Avg rating:3.0/5.0
Slides: 83
Provided by: gol77
Category:

less

Transcript and Presenter's Notes

Title: EJB Design Patterns


1
EJB Design Patterns
  • Vijay Bhatt
  • NCST Juhu, Mumbai

2
EJB Design Patterns
  • Best practice solution to commonly
  • recurring problems.
  • Enable us to design efficient, scalable and
  • maintainable systems

3
Benefits
  • Provides a high-level language to discuss design
    issues.
  • Provides much of the design.
  • Combinations of patterns form reusable
  • architectures.

4
Categories
  • 1) EJB Layer Architectural patterns
  • Architecture or partitioning of logic
  • Session Façade
  • Message Façade
  • EJB Command
  • Data Transfer Object Factory
  • Generic Attribute Access
  • Business Interface

5
Categories
  • 2) Inter-tier Data Transfer Patterns
  • For transferring data from the client to the
  • server and back.
  • Data Transfer Object
  • Domain DTO
  • Custom DTO
  • Data Transfer Hashmap
  • Data Transfer Rowset

6
Categories
  • 3) Transaction and Persistence Patterns
  • transaction control, persistence and
    performance




    related
  • Version Number
  • JDBC for reading
  • Data Access Command Bean/Data Access Object
  • Dual Persistent Entity Bean

7
Categories
  • 4) Client-side EJB Interaction Patterns
  • maintainability and performance from client
  • point of view.
  • EJB Home Factory
  • Business Delegate

8
Session Façade
9
Background
  • Fine-grained access through remote interfaces
  • increases network traffic and latency.
  • Overhead of multiple network calls
  • Processes involve multiple business objects.
  • Data access and business logic scattered across
    clients.
  • Tight coupling between classes.
  • Decrease in flexibility and design clarity.
  • Transactions not safe When calling an entity
    beans methods directly, each method call is a
    separate unit of work, and a separate
    transaction.
  • Transaction not maintained across methods.

10
Need
  • Invoke methods of multiple session or entity
    beans in one transaction and one bulk network
    call.

11
Issue
  • How can an EJB client execute a Use cases
    business logic in one transaction and one bulk
    network call?

12
Solution 1
  • Put extra logic into our entity beans to perform
  • many operations on behalf of a single client
    call.
  • This solution introduces maintenance problems,
  • because our entity bean layer will likely be
    used in
  • many different ways over time.
  • Merging our application logic (verbs) with our
    persistence logic (nouns), which is poor
    application design.

13
Solution 2
  • Client demarcates a large transaction via the
    Java
  • Transaction API (JTA).
  • High network overhead.
  • Poor concurrency.
  • High coupling.
  • Poor reusability. Other clients cannot
    reuse
  • Mixing of presentation logic with business
    logic.
  • Poor maintainability. Usage of the Java
    Transaction API

14
The Solution
  • A server-side abstraction that serves as an
  • intermediary, and buffers calls to entity
    beans.
  • Session beans will contain application logic to
  • fulfill use-cases.
  • Each session bean performs bulk operations on
  • entity beans on behalf of a single client
    request.
  • Clients have access to session beans only, not
  • entity beans.

15
Advantages
  • Low network overhead.
  • Lower overall overhead on client end.
  • Session bean is the transactional façade,
    localizes
  • transactions to the server-side, and keeps
    them
  • short, giving higher concurrency.
  • Lower coupling.
  • Entity beans remain reusabe.
  • Better maintainability Clean separation of
  • middleware (transaction) and application
    logic.
  • Clean verb-noun separation.

16
Role of Use Cases
  • Do not map every use case to a session façade.
  • Consolidate them into fewer session beans based
    on some logical partitioning.
  • Design session facades to aggregate a group of
    the related interactions into a single session
    façade.
  • The use cases Create New Account, Change Account
    Information, View Account information, and so on
    all deal with the coarse-grained entity object
    Account.
  • For a banking application, group the interactions
    related to managing an account into a single
    session façade called AccountSessionFacade.

17
Message Façade
  • For asynchronous use cases.

18
Issue
  • How can an EJB client invoke methods of multiple
    session or entity beans with one transaction,
    without need to block wait for responses for
    each bean?

19
Solution
  • Use a message driven beans to create a
    fault-tolerant asynchronous façade
  • Clients should have access to message driven
    beans only not to entity beans.

20
EJB Home Factory
21
Background
  • Multiple lookups of the same home are redundant.
  • Home is used only once
  • an EJBHome never goes stale and can be
  • reused for the lifetime of the client
    application.
  • Requires a network call if JNDI server is on
  • a different machine.

22
Issue
  • How can a client lookup an EJBHome only once in
    the lifetime of its application and abstract the
    details of lookup?

23
Solution
  • Abstract EJBHome lookup code into a reusable
    EJBHomeFactory which can cache EJBHomes for
    lifetime of the client application.

24
Solution
  • Place EJB Home lookup code into a reusable EJB
    Home Factory, which can cache EJB Homes for the
    lifetime of a client application.
  • Reuse the same EJB home instance throughout the
    life time of the client.
  • Plain java class.
  • Singleton

25
Client code
  • AccountHome anAccountHome
  • (AccountHome)EJBHomeFactory.getFactory().
  • lookUpHome(AccountHome.class)
  • import javax.ejb.
  • import java.rmi.
  • import java.util.
  • import javax.naming.
  • public class EJBHomeFactory
  • private Map ejbHomes

26
  • private static EJBHomeFactory aFactorySingleton
  • Context ctx
  • private EJBHomeFactory() throws NamingException
  • ctx new InitialContext()
  • this.ejbHomes Collections.synchronizedMap
  • (new HashMap())
  • public static EJBHomeFactory getFactory()
  • throws NamingException
  • if ( EJBHomeFactory.aFactorySingleton null )
  • EJBHomeFactory.aFactorySingleton
  • new EJBHomeFactory()
  • return EJBHomeFactory.aFactorySingleton

27
  • public EJBHome lookUpHome(Class homeClass)
  • throws NamingException
  • EJBHome anEJBHome (EJBHome)
  • this.ejbHomes.get(homeClass)
  • if(anEJBHome null)
  • anEJBHome (EJBHome) javax.rmi.PortableRemoteObje
    ct.narrow
  • (ctx.lookup(homeClass.getName()),homeClass)
  • this.ejbHomes.put(homeClass, anEJBHome)
  • return anEJBHome

28
Business Delegate
29
Background
  • When using Session and/or MessageFaçade, the
    client is coupled to the EJBlayer, creating
    dependencies between clientand server.

30
Problems
  • Complicates client logic with complex error
    handling.
  • NamingExceptions, RemoteExceptions,EJBExceptio
    n to be caught
  • Couples the clients directly to EJB and JMS
    APIs.
  • Lookup and exception handling code
  • Dependency of client and server programmers on
    availability of the complete and compiled session
    bean layer.
  • Client programmers depend on the implementation
    of the Session Façade in order to compile and
    test their code.

31
Cont
  • Places recovery responsibility on clients.
  • When a transaction fails.
  • May not be necessary to propagate this error
    to
  • the end application user and ask them to
    retry.
  • Instead, client code may automatically
    re-execute
  • the transaction.
  • Client code needs to be explicitly aware of
  • catching these transactions and re-trying
    them.

32
Issue
  • How can intermediary between client the session
    façade be created to facilitate decoupling the
    client from the EJB layer?

33
Solution
  • Create a layer of business delegates plain java
    classes that hide EJB API complexity by
    encapsulating code that required to discover,
    delegate to and recover from invocation on the
    session and message façade EJB layer

34
Solution
  • Client-side Intermediary between a client
  • and the Session Façade.
  • Introduce intermediate class business delegate to
    decouple business components from the code that
    uses them.
  • Manages the complexity of distributed component
    lookup, exception handling and recovery
  • Adapts the business component interface to a
    simpler interface for use by views.
  • Plain java classes

35
How?
  • Clients locally invoke methods on the BD
  • BD delegates directly to a method with the
  • same signature on the session façade, or
  • populate a JMS message and send it to the
  • Message Façade.
  • Maps one-to-one to session beans
  • Wrap multiple message driven beans.

36
Functions of BD
  • Delegate method calls to an EJB.
  • Hide EJB specific system exceptions.
  • RemoteException and EJBException
  • JMS exceptions are caught in the business
    delegate and re-thrown to the client as a non-ejb
    specific exceptions,such as a BusinessDelegateExce
    ption.
  • Application level exceptions are passed to the
    client.
  • Cache data locally.
  • Transparently re-try failed transactions.
  • Prototype business delegates can be written that
  • simply return dummy data.

37
EJB Command
38
EJB Command
  • Developing with a session façade and business
    delegates can result in long change-deploy-test
    roundtrips, which can become a bottleneck in a
    large project.
  • The crux of the problem is that the business
  • logic is being placed in a layer of session
    EJBs, which can be pretty heavy weight to
    develop with.

39
Issue
  • How can a developer implement use cases business
    logic in a lightweight manner to achieve all
    benefits of session façade business delegate

40
The Command Pattern
  • Wrap business logic in lightweight command
    objects
  • Decouple the client from EJB
  • Execute in one network call
  • Act as a façade to the EJB layer
  • Plain java class with gets, sets and an execute
    method.

41
How?
  • Clients interact with the command object locally
  • Execute within a remote EJB server,transparently
    to the client.
  • Encapsulate individual units of work in an
    application.
  • A use cases business logic encapsulated in a
    command.

42
Command
  • Client creates a Command
  • Client sets attributes onto the command
  • Client calls the commands execute method
  • Client calls gets on the command until it has
    retrieved all the data resulting from the
  • execution of the command/use case.

43
Interaction
  • The client instantiates the command object
  • The client calls an executeCommand method on the
    routing logic/CommandExecutor
  • The CommandExecutor delegates the call to an
  • EJBCommandTarget (part of routing logic)
  • The command target knows how to send the
  • command to the command server
  • CommandServer is a stateless session bean.
  • CommandServer calls the execute method on the
  • command, which then goes about its business
    logic.

44
Benefits
  • Rapid Application Development (RAD)
  • Separation of business logic from presentation
  • logic.
  • Forces execution of use cases in single
    roundtrip.
  • Decouples client from EJB.
  • Commands can execute locally or produce
  • dummy data.
  • Allows multiple return values.

45
Disadvantages
  • Very coarse-grained transaction control.
  • Commands can only run under the transaction
    settings of the CommandServer that executes them
    (as they are just plain java beans). The
    workaround for this is to deploy multiple command
    server session beans with different jndi names
    and transaction settings (configured in the
    deployment descriptors).
  • Cant use security Since business logic is
    embedded in the command beans.
  • Commands can become unmanageable on large
  • projects.

46
Data Transfer ObjectorValue Object
47
Exchange of data
  • Read data from the server for displaypurposes
  • Change some data on the server by
    creating,updating or removing data.

48
Need
  • Transfer bulk data with the server.
  • Many parameters in a method call.
  • Client gets multiple attributes from a
    session or
  • entity bean by executing multiple
    fine-grained
  • calls to the server.

49
Problem
  • Each call to the server is a network call
  • Blocking on the client while the EJB server
  • intercepts the call to the server and
    performs
  • transaction and security checks and retrieval
  • Each method call executes in its own separate
    transaction if the client is not using Java
    Transaction API client demarcated transactions.

50
Issue
  • How can a client exchange bulk data without the
    server making multiple fine-grained network calls?

51
Solution
  • Create plain java classes called Value Objects or
    DTOs, which contain and encapsulate bulk data in
    one network transportable bundle.
  • A value object is a plain serializable Java class
    that represents a snapshot of some server side
    data
  • Granularity
  • Domain Value Objects
  • Custom Value Objects

52
DTO Factory
53
Need
  • When value objects change very often.
  • Value object creation and consumption logic
    should be implemented so as to minimize the
    impact of frequent changes in the value objects
    on the rest of the system.

54
Problem
  • Value Objects have a tendency to change often.
  • Domain Value Objects change whenever the
  • domain objects change (adding a new attribute
    to
  • an entity bean, etc).
  • Custom Value Objects are just use case specific
  • data holders for transporting data across a
  • network they can change as frequently as
    your
  • applications presentation view.
  • Tens to hundreds of different Value Objects, each
    of which would require custom logic to create it.
  • How and where should this logic be implemented?

55
Issue
  • How should a DTO creation and consumption logic
    be implemented inorder to minimize the impact of
    frequent changes in the DTO layer on the rest of
    the system?

56
Solution 1
  • getXXXValueObject / setXXXValueObject
  • methods directly on entity beans.
  • Tightly couples the value object layer to the
  • entity bean layer.
  • Every time a web page changed and a different
  • view of the data model was required, you
    would
  • have to add a new method to an entity bean,
  • recompile your entity bean, and redistribute
    your
  • remote interfaces to any client using them.
  • Entity beans are are no longer reusable.

57
Solution
  • Place the resposibility of creating and consuming
    data transfer objects in a data transfer object
    factory
  • Two fundamental ways to implement DTO depending
    on the client,
  • Stateless session bean (for non-ejb clients)
  • Plain java class (for ejb clients)

58
Benefits
  • Separates the logic related to Value Objects
    (part
  • of the application domain) from other
  • components in your system such as entity
    beans
  • (part of the business domain).
  • When new views or different subsets of server
    side data become necessary, new value object
  • creation methods can be added to the
  • ValueObjectFactory.
  • The entity beans themselves do not need to know
  • about these different views of their data.
  • Enables entity bean reuse.

59
  • JDBC for Reading

60
JDBC for Reading
  • Present static server-side data to a client in
  • tabular form.
  • Read-only

61
Problems
  • The n1 entity bean database calls problem.
  • With BMP and certain implementations of CMP,
  • retrieving data from N entity beans require
    N1
  • database calls.
  • finder method (one database call).
  • ejbLoad() individually on each entity bean
    returned by the finder method, lock a db conn
    of the pool, n/w call.
  • Employee and Departments example 2N1
  • database calls

62
Cont
  • Require tens of lines of code
  • Significantly slow down a system due to
  • the database calls
  • remote calls
  • overhead incurred for traversing multiple
    entity bean relationships

63
Issue
  • How can relational data be transferred to the
    client in a generic tabular format?

64
Solution 1
  • Employee and a Department entity bean.
  • getEmployees() method on a Session Façade
  • finder method on an EmployeeHome object
  • find each employees related department entity
  • bean
  • Create a Custom Data Transfer Object with the
  • combined data from these two entity beans.
  • Session bean returns a collection of
  • EmployeeDepartmentDTOs.

65
Need
  • Client side mainly requires tabular data for read
  • only, listing purposes
  • Using local interfaces will reduce the
    performance
  • problems
  • Querying through the entity bean layer for simply
  • listing of read only data causes unacceptable
  • performance problems
  • In BMP, perform listing operations on relational
  • databases using JDBC.

66
Cont
  • Using JDBC to directly read the rows and columns
  • required by the client can be far faster and
    more
  • efficient then going through the entity bean
    layer.
  • Entire table of employees and departments could
  • be bulk-read in just one JDBC call from the
  • database
  • After reading in the ResultSet return using,
  • EmployeeDepartmentDTO
  • HashMaps
  • RowSets

67
Benefits
  • Perform queries in ONE BULK READ.
  • Takes advantage of DB built in caching.
  • The next time a query is run, the one bulk JDBC
  • query will come directly from the database
    cache.
  • Retrieve the exact data your use case requires.
  • Using JDBC, you can select the exact columns
  • required across any number of tables.

68
  • Data Transfer HashMap

69
Data Transfer HashMap
  • A client needs to exchange bulk data with
  • the server in a generic fashion.

70
Problems with DTO
  • Minimizing on the number of network calls
  • Data Transfer Objects help in this.
  • new DTO for every new use case
  • High cost to change new DTOs and associated
    creation logic must be written.
  • Data Transfer Objects create a new layer, which
  • can explode to thousands of objects in a
    large
  • application.
  • Changes in entity bean attributes will cause
    ripples that could require changes in multiple
    DTOs as well.
  • Client UIs tightly coupled to the server.

71
Solution
  • Use HashMaps to marshal arbitrary sets of
  • data between client and EJB tier.
  • Plain JDK HashMaps provide a generic,
    serializable container for arbitrary sets of
    data, that can replace an entire layer of Data
    Transfer Objects.
  • The only dependency been client and server side
  • code is the naming conventions placed on the
  • keys used to identify attributes, described
    later in
  • this pattern.
  • Clients request HashMaps by going through the
  • Session Façade.

72
Benefits
  • Excellent maintainability - eliminates the
  • Data Transfer Object layer.
  • One data object (Map) across all clients. Using a
    Map as a data container significantly reduces the
  • complexity of the JSP code, as pages dont
    need
  • to be written with use case specific Value
    Objects
  • that are tightly coupled to the entity bean
    layer.
  • Low cost of maintenance over time. New views of
    server side data can be created that does not
    require any server side programming. Clients can
    dynamically decide which attributes to display.

73
  • Data Transfer Rowset

74
Data Transfer RowSet
  • When using JDBC for Reading, relational
  • data needs to be transferred across the
  • network tier from the Session Façade to the
  • client.
  • How can relational data be transferred to the
  • client in a generic, tabular format?

75
Cont
  • Session bean performs a JDBC call to get a
  • ResultSet that contains information about an
    employee and their department.
  • Session bean manually extracts fields from the
  • ResultSet and calls the necessary setters to
    populate the DTO.
  • Each row in the ResultSet will be transferred
    into
  • a DTO which will be added to a collection.
  • This collection of DTOs now forms a network
  • transportable bundle, transferable to the
    client for
  • consumption.

76
Problem
  • Tabular to OO and back to tabular is
  • redundant.
  • Preserve the tabular nature of the data being
  • transferred in a generic fashion, allowing
  • for simpler clients and simpler parsing into
  • the client UI.

77
Solution
  • Use RowSets for marshalling raw relational
  • data directly from a ResultSet in the EJB
  • tier to the client tier.
  • Rowsets implementations which do not keep a live
    connnection with database can be used to copy
    ResultSet data and bring the
  • data down to the client tier.
  • http//www.onjava.com/pub/a/onjava/2004/06/23/cach
    edrowset.html
  • http//java.sun.com/j2se/1.5.0/docs/api/javax/sql/
    rowset/CachedRowSet.html

78
Advantages
  • Provides a common interface for all query
  • operations.
  • All the clients can use the same interface for
  • all data querying needs.
  • No matter what the use case is or what data is
    being returned, the interface a client operates
    on stays the same.
  • Eliminates the redundant data translation.

79
  • Data Access Object

80
Problem
  • Access to data varies depending on the source of
  • the data. Access to persistent storage, such
    as to a
  • database, varies greatly depending on the
    type of
  • storage (relational databases,
    object-oriented
  • databases, flat files, and so forth) and the
    vendor
  • implementation.
  • Code that depends on specific features of data
  • resources ties together business logic with
    data
  • access logic. This makes it difficult to
    replace or
  • modify an application's data resources.

81
Benefits
  • Separates a data resource's client interface
  • from its data access mechanisms
  • Adapts a specific data resource's access API
  • to a generic client interface
  • Allows data access mechanisms to change
  • independently of the code that uses the data.

82
References
  • EJB Design Patterns by Floyd Marinescu -
    Wiley.(available online at www.theserverside.com
    and \\Kalpa)
  • J2EE Design Patterns Catalog -
  • http//java.sun.com/blueprints/patterns/cata
  • log.html
  • Core J2EE Patterns (online book)
    -http//java.sun.com/blueprints/corej2eepatte
  • rns/Patterns/
  • Sun Java Center J2EE Patterns -http//developer.ja
    va.sun.com/developer/rest
  • ricted/patterns/J2EEPatternsAtAGlance.html
Write a Comment
User Comments (0)
About PowerShow.com