640 likes | 653 Views
Learn essential patterns for designing and managing Enterprise JavaBeans applications efficiently and effectively. Includes solutions for handling long transactions, entity and service components, event listeners, and more.
E N D
Patterns for buildingfast and scalableEJB applications • Markus Voelter, MATHEMA AG • markus.voelter@mathema.de • Patterns written by Voelter, Wolff, Schmid
What is a pattern? • Each pattern is a three-part rule, which expresses a relation between a certain context, a certain system of forces which occurs repeatedly in that context, and a certain software configuration which allows these forces to resolve themselves. • Jim Coplien
What is a pattern? • patterns have become part of the mainstream • patterns for software design • patterns for software architecture • organizational patterns • pedagogical patterns
Contents 1. Architecture 2. Dependencies 3. Internal 4. Large Systems 5. Persistence 6. State Access 7. Variability
Contents 1. Architecture 2. Dependencies 3. Internal 4. Large Systems 5. Persistence 6. State Access 7. Variability
Long Transaction • Problem: Long transactions occur • Many locks, bad performance • Solution: Use a Stateful Session Bean to collect that data • Database work is done in the final method call • Drawbacks • Probably database checks are needed to ensure validity of transaction • Isolation might be broken • Optimistic locking i.e. lots of conflicts might occur
Long Transaction II • Example: Shopping Cart • Items added, transaction commited at the end
Process As Entity Bean • Problem: Business Process with complex state, very long run time and/or collaboration of multiple users • Stateful Session Beans can not be shared and have a short life time • Solution: Use an Entity Bean instead • Can be shared and is persistent
Process As Entity Bean Example • Example: Travel Expense Report • Employee, bookkeeper, boss etc. collaborate • Can take quite some time...
Service Component Facade • Problem: Transactions across Entity Bean methods and collaborations between Entity Bean methods cannot be defined • Solution: Use a Stateless Session Bean that accesses the Entity Beans • One Session Bean method calls multiple Entity Bean methods • Transactions and collaborations can be expressed • Original Facade pattern tries to hide complexity • Here collaboration is expressed • Example: Transfer between accounts
Service Component Facade • Problem: Transactions across Entity Bean methods and collaborations between Entity Bean methods cannot be defined • Solution: Use a Stateless Session Bean that accesses the Entity Beans • One Session Bean method calls multiple Entity Bean methods • Transactions and collaborations can be expressed • Original Facade pattern tries to hide complexity • Here collaboration is expressed • Example: Transfer between accounts You can use Home Operations for this purposeThe Entity Beans might have only local interfaces EJB 2.0 Note
Type Manager • Problem: Entity Beans are expensive • Concurrency, synchronization, lifecycle management • Cannot be switched off if not needed • Solution: Session Bean that works directly on the database • Data represented as Data Transfer Objects • Primary Key used to identify entities • Primary Key passed to every method • Example: Stock watch (get/set quote) • Drawbacks • Container services for Entity Beans not used i.e. Container Managed Persistence, optimizations for database access etc.
Type Manager II • Entity-Version: • Person p = home.findByPrimaryKey( aKey );p.setName( “Potter” );p.setFirstName( “Harry” ); • Type-Manager Version: • PersonManager pm = home.create();pm.setName( aKey, “Potter” );pm.setFirstName( aKey, “Harry” ); - or better –pm.setNames( aKey, “Potter”, “Harry” );
Contents 1. Architecture 2. Dependencies 3. Internal 4. Large Systems 5. Persistence 6. State Access 7. Variability
Event Listener • Problem: Mutual or circular dependencies are bad • Reusability • Maintenance and deployment problems • How can lower layer communicate with higher layers? • Solution: Method call in one way, event communication back • Message driven Beans (EJB 2.0) are not enough: no methods, only events • Drawbacks • Performance degradation: Cascade of events as result of a method call
Event Listener Example • Example: Customer must be notified about payment of order
Relationship Service • Problem: Every Entity Bean must provide methods to access related entities • Often changes to implementation and interface are needed • Solution: Externalize the relations into a Relationship Service • Can store different types of relationships and attributes • Example: Implementation as Entity Bean using Bean Managed Persistence • Drawbacks • Entities are not entirely self-contained • Depend on Relationship Service • Explicit access to Relationship Service needed
Relationship Service • Problem: Every Entity Bean must provide methods to access related entities • Often changes to implementation and interface are needed • Solution: Externalize the relations into a Relationship Service • Can store different types of relationships and attributes • Example: Implementation as Entity Bean using Bean Managed Persistence • Drawbacks • Entities are not entirely self-contained • Depend on Relationship Service • Explicit access to Relationship Service needed EJB 2.0 entity bean relationshipsgo in this direction. However, you cannot store additional information with them EJB 2.0 Note
Contents 1. Architecture 2. Dependencies 3. Internal 4. Large Systems 5. Persistence 6. State Access 7. Variability
Data Access Object • Problem: Bean Managed Persistence leads to mix of business logic and database access • Beans become complex • Hard to test • Hard to adapt to different databases • Solution: Add a class to handle persistence • Lifecycle methods call this class • Example: CustomerDAO • Implements ejbCreate(), ejbStore(), etc. • Includes the attributes • Drawbacks • Component implementation is more complex
Data Access Object • Problem: Bean Managed Persistence leads to mix of business logic and database access • Beans become complex • Hard to test • Hard to adapt to different databases • Solution: Add a class to handle persistence • Lifecycle methods call this class • Example: CustomerDAO • Implements ejbCreate(), ejbStore(), etc. • Includes the attributes • Drawbacks • Component implementation is more complex EJB 2.0 CMP hasimproved significantly – you will use it more often, so BMP-DAOs are less important. EJB 2.0 Note
Dependent Object • Problem: Entity Beans has fine grained internal structure • Attributes form semantic groups • Groups are not independent entities themselves • Solution: Partition the state of an Entity Bean into several dependent objects • Each object represents a semantic group • Drawbacks • Identification e.g. for deleting dependent objects is often hard • Compare values • Use IDs invisible to client • Work on complete list of dependent objects
Dependent Object You may want to use Local Entity Beans in EJB 2.0. Dependent objects can also be used as DTO‘s (see later), which is not possible with Local Entity Beans. EJB 2.0 Note • Problem: Entity Beans has fine grained internal structure • Attributes form semantic groups • Groups are not independent entities themselves • Solution: Partition the state of an Entity Bean into several dependent objects • Each object represents a semantic group • Drawbacks • Identification e.g. for deleting dependent objects is often hard • Compare values • Use IDs invisible to client • Work on complete list of dependent objects
Dependent Object II • Example: Person and telephone numbers, Email addresses
Wrapped Business Object • Problem: Complex Business Logic in beans • Developing, testing or debugging requires deployment • Solution: Add a class to hold the business logic (Business Object) • Bean delegates to Business Object • Testing and debugging directly on Business Object • Example: Customer • All calls delegated • Wrapped Business Object is created in ejbLoad()/ejbCreate() • Drawbacks • Additional class and interfaces (more complex)
Contents 1. Architecture 2. Dependencies 3. Internal 4. Large Systems 5. Persistence 6. State Access 7. Variability
Business Component • Problem: Some EJBs are always used together as a group • No formal grouping • Clients must operate on many components • Solution: Provide a Business Component consisting of multiple EJBs internally • Distributed and released as one subsystem • Facade as single access point • Facade might use Weakly Typed Interface • Example: Order Business Component contains Order, OrderBulkReader, OrderWebInfo, OrderItem, OrderInfo
Administratable Component • Problem: In addition to business logic, administrative, setup or diagnosis methods are also needed • Component must include everything to work properly • Clients should only be able to call business logic • Solution: Implement administration, setup and test but allow access only to administrators • Remote interface as subclass of business and administrative interface • Additional Beans • Probably GUI interface • Example: Logging, self-test, database table creation of an Order
Configuration Service • Problem: Related components usually have some aspect of their configuration in common • Technical or functional • Specifying these in the Deployment Descriptor is inefficient and error prone • Solution: Provide a central Configuration Service • Each component accesses it • Also client can access it • Example: OrderConfigService (Currency, VAT rate, DataSources etc.) for Orders
Request Hub • Problem: Component must know which other component is responsible for a specific task • Independent evolution is hard • Component must know other components' interfaces • Solution: Provide a central component which receives each request and forwards it to the correct receiver • Can mask different communication protocols • Parameter and data types can be adapted • Example: Generic Request Hub with configurable request handlers • Drawbacks • If responsibilities change so must the hub
Roll-your-own Interception • Problem: Some aspects are not supported by the Container, but must be used in every Bean • More complex access rules than EJB provides • Performance measurements (method runtime) • Solution: Create an Interception interface • Code generation to create wrapper Bean implementations • Calls pre- and postoperations • Calls real implementation • Example: Generic Interceptor, Access control for Beans • Drawbacks • Code generation is often complex
Trader • Problem: Usually components are looked up by name not by what they provide • Static, no adaptation to changing environment • Solution: Provide a Trader that does lookups by properties • Example: Printer lookup • Drawbacks • Trader must find matches, lookup Home Interface i.e. overhead • Home Handle can be used instead
Contents 1. Architecture 2. Dependencies 3. Internal 4. Large Systems 5. Persistence 6. State Access 7. Variability
Deferred Store • Problem: Frequent database updates even though Entity Beans do not change • Performance problems • Solution: Only store the state in the database if it was changed • Introduce a flag to keep track of changes • Solution if business logic is implemented: • Provide class with private instance variables and public access method • Access methods change flags accordingly • Business logic is implemented in subclass • Business logic must use access method • Thus flags will be changed • Example: Customer Flag per instance or per attribute
Historized State • Problem: Old data must be kept • Data of Entity Beans is usually deleted (ejbRemove()) • Solution: Implement Entity Components in a way that data is kept instead of deleted or changed • Timestamp or version must be introduced • Deleted data is only marked as deleted • Example: Customer • ejbCreate(), ejbRemote() • ejbLoad(), ejbStore()
Lazy State • Problem: Loading the state of complex Entity Beans takes a lot of time • Lots of data is loaded • Only parts are needed • Solution: Do not load the entire state in ejbLoad() • Load the state on demand • E.g. in accessor methods • Example: Purchases of a customer • Drawbacks • Makes only sense if loading the complete data is much more expensive then loading only parts • One large database operation is replaced by multiple small
Middle Tier Cache • Problem: Slow database connection (e.g. legacy system) can become a bottleneck • Probably only parts of the database are used • Solution: Install a Middle Tier Cache • Pre-loads data from backend • Entity Beans use cache only • Cache writes changes back • Different implementations possible • Drawbacks • In multiserver environments only one cache should exist or synchronization must be dealt with • Examples: Bought tools
Contents 1. Architecture 2. Dependencies 3. Internal 4. Large Systems 5. Persistence 6. State Access 7. Variability
Bulk Setter • Problem: Repeated invocations of setter methods are inefficient • Remote communication, transaction and security handling • Solution: Provide an additional operation (Bulk Setter) that takes a group of attributes as parameters • Person: setPersonInput(name, firstName, dateOfBirth)
Bulk Setter II • Standard-Version:public interface Person extends EJBObject { ... void setName(String name) throws RemoteException; void setFirstName(String firstName) throws RemoteException; void setDateOfBirth(Date dateOfBirth) throws RemoteException; ...} • Bulk-Setter-Version:public interface Person extends EJBObject { ... void setPersonData(String name, String firstName, Date dateOfBirth) throws RemoteException; ...}
Data Transfer Object (DTO) • Problem: Repeated invocations of getter methods are inefficient • Remote communication, transaction and security handling • Solution: Add a class that contains all attributes that are usually read together • Add a Factory method to the Entity Bean to read a Data Transfer Object • Example: PersonValueObject • Constructor, getter / setter • Drawback • Bean internal data on the client • Changes are not detectable on the client • Data Transfer Objects depend on Use Cases • Might change
Data Transfer Object II • Standard-Version:public interface Person extends EJBObject { ... String getName() throws RemoteException; String getFirstName() throws RemoteException; Date getDateOfBirth() throws RemoteException; ...} • DTO-Version:public interface Person extends EJBObject { ... void PersonData getPersonData() throws RemoteException; ...}
Bulk Reader • Problem: Client must retrieve lots of entities (e.g. for display) • Accessing each entity as an Entity Bean or through a Type Manager is inefficient • Solution: Provide a Session Component with finder methods • Use direct database access • Return list of Data Transfer Objects • Example: Product: All products of a certain category • Drawbacks • Changes in the entity structure affect the Entity Bean and the Bulk Reader
Bulk Reader • Problem: Client must retrieve lots of entities (e.g. for display) • Accessing each entity as an Entity Bean or through a Type Manager is inefficient • Solution: Provide a Session Component with finder methods • Use direct database access • Return list of Data Transfer Objects • Example: Product: All products of a certain category • Drawbacks • Changes in the entity structure affect the Entity Bean and the Bulk Reader Can be implemented as Home Operations in EJB 2.0. EJB 2.0 Note