Download presentation
Presentation is loading. Please wait.
Published byArchibald White Modified over 9 years ago
1
Distributed Object-Oriented Programming (3) – Enterprise JavaBeans SNU iDB Lab. Taewhi Lee May 14th, 2007
2
Review – Distributed Programming Paradigm Shift Socket RPC CORBA RMI CORBA Component Model OOP CBD Object – limited reusability Component – independent service Several components are plugged in to a component architecture system Structured Programming OOP SP – Complexity of system modeling Difficulty in code change/extension OOP – Natural object modeling Reusability by inheritance Flexibility by polymorphism Distributed Component Model Distributed Object Model Basic Inter-Process Communication Distributed Structural Model Web Services Service-Oriented Architecture Distributed Computing SOA DC – client/server are tightly coupled SOA – everything is decoupled EJB
3
Outline Java EE EJB Overview Enterprise Beans EJB Programming Changes in EJB 3.0 References
4
Java EE [1/5] Jave EE History 19951998 2004~ Java J2SEJ2EE Java SE Java EE Object- oriented Platform- independent Garbage collection For Stand-alone applications Java 1.2 + Libraries (e.g. GUI, DB, networking) Since Java 1.5 For Distributed enterprise applications J2SE + Libraries (e.g. Security, Transaction)
5
Java EE [2/5] What is Jave EE? Java EE (Java Platform, Enterprise Edition) The industry standard for developing enterprise applications Portable, robust, scalable and secure server-side Java applications Provides web services, component model, management, and communication APIs Java EE goals Highly available – to meet the needs of today’s global business environment Secure – to protect the privacy of users and the integrity of enterprise data Reliable and scalable – to insure that business transactions are accurately and promptly processed
6
Java EE [3/5] Jave EE & EJB Java EE Web Services Technologies Web Application Technologies Management & Security Technologies Enterprise Application Technologies
7
Java EE [4/5] Jave EE Technologies Web Services Technologies Implementing Enterprise Web Services Java API for XML-Based Web Services (JAX-WS) 2.0 Java API for XML-Based RPC (JAX-RPC) 1.1 Java Architecture for XML Binding (JAXB) 2.0 SOAP with Attachments API for Java (SAAJ) Streaming API for XML Web Service Metadata for the Java Platform Web Application Technologies Java Servlet 2.5 JavaServer Faces 1.2 JavaServer Pages 2.1 JavaServer Pages Standard Tag Library
8
Java EE [5/5] Jave EE Technologies (cont’d) Enterprise Application Technologies Enterprise JavaBeans 3.0 J2EE Connector Architecture 1.5 Common Annotations for the Java Platform Java Message Service API The Java Database Connectivity API (JDBC) Java Persistence API Java Transaction API (JTA) JavaBeans Activation Framework (JAF) 1.1 JavaMail Management and Security Technologies J2EE Application Deployment J2EE Management Java Authorization Contract for Containers
9
Outline Java EE EJB Overview Enterprise Beans EJB Programming Changes in EJB 3.0 References
10
EJB Overview [1/11] What are Enterprise JavaBeans? Enterprise JavaBeans (EJB) A standard-based component model APIs to implement business logics EJB design goals Common services Multithreading Transaction management Resource management (e.g., connection pooling) Persistence management Security services Distribution and scalability “Throw money at it” solution
11
EJB Overview [2/11] EJB Architecture EJB architecture Specifies the responsibilities and interactions among EJB entities EJB Server EJB Container Clients Enterprise Bean Enterprise Bean EJB Client EJB Server EJB Container Clients Enterprise Bean Enterprise Bean EJB Client
12
EJB Overview [3/11] EJB Server EJB server Provides a run-time environment Provides system services and manages resources Process and thread management System resources management Database connection pooling and caching Management API EJB Server EJB Container Clients Enterprise Bean Enterprise Bean EJB Client
13
EJB Overview [4/11] EJB Container EJB container Provides a run-time environment for an enterprise bean Likely provided by server vendor Hosts the EJBs and provides services to EJBs Naming Life cycle management Persistence (state management) Transaction Management Security EJB Server EJB Container Clients Enterprise Bean Enterprise Bean EJB Client
14
EJB Overview [5/11] Enterprise Bean Enterprise Bean A specialized component for the real business logic Consists of several classes and interfaces Distributed over a network Server vendors provide tools that automatically generate distribution, transaction and security behavior EJB Server EJB Container Clients Enterprise Bean Enterprise Bean EJB Client
15
EJB Overview [6/11] EJB Client Client access is controlled by the container in which the enterprise bean is deployed Clients locates an enterprise bean through Java Naming and Directory Interface (JNDI) RMI is the standard method for accessing a bean over a network EJB Server EJB Container Clients Enterprise Bean Enterprise Bean EJB Client
16
EJB Overview [7/11] Pros and Cons of EJB Pros Component modularization Reusability ↑, maintenance cost ↓ Component portability “Write Once, Run Anywhere” (WORA) Development simplification A number of tricky middleware services are automatically managed Programmers can concentrate on writing business logic Development speed ↑, code quality ↑ Cons Need to buy EJB container Implementation according to EJB specification
17
EJB Overview [8/11] RMI vs. EJB RMIEJB Business object typeDistributed objectDistributed component Basic communication protocol RMI Business method declaration Remote interface Business method implementation Remote classBean class How to implement business method Remote class directly implements remote interface Delegation Business object construction, destruction, find NoHome interface Middleware services (transaction, security…) NoYes
18
EJB Overview [9/11] Code example: HelloWorld in RMI Remote interface Remote class public interface Hello extends Remote { public String sayHello(String name) throws RemoteException; } public class HelloImpl extends UnicastRemoteObject implements Hello { public HelloImpl() throws RemoteException { } public String sayHello(String name) throws RemoteException { return “Hello, ” + name; }
19
EJB Overview [10/11] Code example: HelloWorld in EJB Home interface Remote interface public interface HelloHome extends EJBHome { public Hello create() throws RemoteException, CreateException; } public interface Hello extends EJBObject { public String sayHello(String name) throws RemoteException; }
20
EJB Overview [11/11] Code example: HelloWorld in EJB (cont’d) Bean class public class HelloBean implements SessionBean { SessionContext ctx; // EJB container contract methods public void ejbCreate() { } public void ejbRemove() { } public void ejbActivate() { } public void ejbPassivate() { } public void setSessionContext(SessionContext ctx) { this.ctx = ctx; } // business method public String sayHello(String name) { return “Hello, ” + name; }
21
Outline Java EE EJB Overview Enterprise Beans EJB Programming Changes in EJB 3.0 References
22
Enterprise Bean [1/7] Types of Enterprise Beans
23
Session bean Implements some business logic Business process component e.g., order, payment in an online shopping mall Entity bean Object-oriented view of entities stored in persistent storage Normally, each instance represents a row in a RDB table e.g., product information, user information Enterprise Bean [2/7] Types of Enterprise Beans
24
Stateful session bean Maintains a state The state is relevant only for a single client Cannot be seen by other clients Expires after a certain timeout e.g., shopping cart Enterprise Bean [3/7] Stateful Session Bean
25
Stateless session bean No state Can have fields, but they are not unique to any client Since the container knows the bean has no state, it can: Use a single bean instance (while each client thinks it has its own copy) Destroy/re-instantiate on the fly Redirect requests to different instances (load balancing) e.g., currency conversion Enterprise Bean [4/7] Stateless Session Bean
26
CMP(Container-Managed Persistence) entity bean Container is responsible for saving the persistent state DB-related classes are auto-generated You specify the container-managed attributes Persistence is independent of the data source The mapping can be applied to other DBs very portable Container can manage caching, locking strategies Can only be used with data sources supported by JDBC Enterprise Bean [5/7] CMP Entity Bean
27
BMP(Bean-Managed Persistence) entity bean The bean writer must provide code for storing/restoring persistent state Less portable Can exploit any persistence framework Not limited to databases Manual tuning can result in performance benefits At the price of portability and hard work Enterprise Bean [6/7] BMP Entity Bean
28
Deployment Process to plug-in enterprise beans to EJB container Jar packaging + plug-in Class files are auto-generated Deployment Descriptor XML file Additional information to run enterprise beans e.g., transaction type, security information Makes it possible to use enterprise beans which are developed by other developers Enterprise Bean [7/7] Deployment Descriptor
29
Outline Java EE EJB Overview Enterprise Beans EJB Programming Changes in EJB 3.0 References
30
Choice of the bean type Session bean? Entity bean? Session bean – Stateful? Stateless? Entity bean – CMP? BMP? Code writing Home interface Remote interface Bean class Primary key class (entity bean only) Deployment descriptor EJB Programming [1/25] EJB Programming
31
Template Example public interface Home extends javax.ejb.EJBHome { public create( ) throws [, …] javax.ejb.CreateException, java.rmi.RemoteException; } public interface CartHome extends EJBHome { public Cart create(String customerName, String account) throws BadAccountException, CreateException, RemoteException; } EJB Programming [2/25] Stateful Session Bean (1/6) Code Example: Shopping Cart – Home Interface
32
Template Example public interface extends javax.ejb.EJBObject { public ( ) throws [, …], java.rmi.RemoteException; } public interface Cart extends EJBObject { public void addItem(int item) throws RemoteException; public void purchase() throws RemoteException; } EJB Programming [3/25] Stateful Session Bean (2/6) Code Example: Shopping Cart – Remote Interface
33
Template public class Bean implements javax.ejb.SessionBean { public ( ) throws [, …], java.rmi.RemoteException { { /* implementation */ } // … other business methods // EJB container contract methods public void ejbCreate ( ) … { /* implementation */ } private SessionContext _context; public void setSessionContext(SessionContext ctx) { _context = ctx; } public void ejbRemove() { /* implementation */ } public void ejbActivate() { } public void ejbPassivate() { } } EJB Programming [4/25] Stateful Session Bean (3/6) Code Example: Shopping Cart – Bean Class
34
Example public class CartBean implements SessionBean { private SessionContext _context; private String customerName, account; // to maintain state information public void setSessionContext(SessionContext ctx) { _context = ctx; } public void ejbCreate (String customerName, String account) { this.customerName = customerName; this.account = account; } public void ejbRemove() { } public void ejbActivate() { /* implementation for activation */ } public void ejbPassivate() { /* implementation for de-activation */ } public void addItem(int item) { /* implementation */ } public void purchase() { /* implementation */ } } EJB Programming [5/25] Stateful Session Bean (4/6) Code Example: Shopping Cart – Bean Class (cont’d)
35
Cart demo.j2ee. CartHome demo.j2ee. Cart demo.j2ee.CartBean Stateful Container EJB Programming [6/25] Stateful Session Bean (5/6) Deployment Descriptor – Shopping Cart
36
Context initialContext = new InitialContext(); // Get the reference of the home object using JNDI CartHome cartHome = (CartHome)PortableRemoteObject.narrow( initialContext.lookup(“java:comp/env/ejb/cart”), CartHome.class); // Create EJB object Cart cart = cartHome.create(“John”, “7506”); cart.addItem(96);// business method call cart.purchase(); EJB Programming [7/25] Stateful Session Bean (6/6) Code Example: Shopping Cart – Client code
37
Template Example EJB Programming [8/25] Stateless Session Bean (1/5) Code Example: Currency Converter – Home Interface public interface Home extends javax.ejb.EJBHome { public create() throws javax.ejb.CreateException, java.rmi.RemoteException; } public interface CurrencyConverterHome extends EJBHome { public CurrencyConverter create() throws CreateException, RemoteException; }
38
Template Example public interface extends javax.ejb.EJBObject { public ( ) throws [, …], java.rmi.RemoteException; } public interface CurrencyConverter extends EJBObject { public double convertUsdToWon(double usd) throws RemoteException; } EJB Programming [9/25] Stateless Session Bean (2/5) Code Example: Currency Converter – Remote Interface
39
Template public class Bean implements javax.ejb.SessionBean { public ( ) throws [, …], java.rmi.RemoteException { { /* implementation */ } // … other business methods // EJB container contract methods public void ejbCreate() … { /* implementation */ } private SessionContext _context; public void setSessionContext(SessionContext ctx) { _context = ctx; } public void ejbRemove() { /* implementation */ } public void ejbActivate() { } public void ejbPassivate() { } } EJB Programming [10/25] Stateless Session Bean (3/5) Code Example: Currency Converter – Bean Class
40
Example public class CurrencyConverterBean implements SessionObject { private SessionContext _context; private static final double WON_PER_USD = 950; public void setSessionContext(SessionContext ctx) { _context = ctx; } public void ejbCreate () { } public void ejbRemove() { } public void ejbActivate() { } public void ejbPassivate() { } public double convertUsdToNis(double usd) { return usd * WON_PER_USD; } EJB Programming [11/25] Stateless Session Bean (4/5) Code Example: Currency Converter – Bean Class (cont’d)
41
CurrencyConverter demo.CurrencyConverterHome demo.CurrencyConverter demo.CurrencyConverterBean Stateless Container EJB Programming [12/25] Stateless Session Bean (5/5) Deployment Descriptor – Currency Converter
42
EJB Programming [13/25] Session Bean Lifecycle
43
Template EJB Programming [14/25] CMP Entity Bean (1/6) Code Example: Product – Home Interface public interface Home extends javax.ejb.EJBHome { public create( ) throws [, …] javax.ejb.CreateException, java.rmi.RemoteException; public findByPrimaryKey( ) throws [, …] javax.ejb.CreateException, java.rmi.RemoteException; public Collection findXXX( ) throws [, …] javax.ejb.CreateException, java.rmi.RemoteException; }
44
Example EJB Programming [15/25] CMP Entity Bean (2/6) Code Example: Product – Home Interface public interface ProductHome extends EJBHome { public Product create(String productId, String description, double price) throws CreateException, RemoteException; public Product findByPrimaryKey(String productId) throws RemoteException, FinderException; public Collection findByPriceRange(double low, double high) throws RemoteException, FinderException; }
45
Example EJB Programming [16/25] CMP Entity Bean (3/6) Code Example: Product – Remote Interface public interface Product extends EJBObject { public void setPrice(double price) throws RemoteException; public double getPrice() throws RemoteException; public String getDescription() throws RemoteException; }
46
Example EJB Programming [17/25] CMP Entity Bean (4/6) Code Example: Product – Bean Class public class ProductBean implements EntityBean { public String productId, description; public double price; private EntityContext context; public ejbCreate(String productId, String description, double price) throws CreateException { if (productId == null) throw new CreateException(“productId required.”); this.productId = productId; this.description = description; this.price = price; return null; }
47
Example (cont’d) EJB Programming [18/25] CMP Entity Bean (5/6) Code Example: Product – Bean Class (cont’d) public void setPrice(double price) { this.price = price; } public double getPrice() { return price; } public String getDescription() { return description; } public void setEntityContext(EntityContext ctx) { this.context = ctx; } public void ejbActivate() { productId = (String)context.getPrimaryKey(); } public void ejbPassivate() { productId = null; description = null; } public void ejbRemove() { } public void ejbLoad() { } public void ejbStore() { } public void unsetEntityContext() { } public void ejbPostCreate(String productId, String description, double price) { } }
48
Container Product demo.ProductHome demo.Product demo.ProductBean java.lang.String Product productId description price productId findByPriceRange select object(o) from Product o where o.price >= ?1 and o.price EJB Programming [19/25] CMP Entity Bean (6/6) Deployment Descriptor – Product
49
Example EJB Programming [20/25] BMP Entity Bean (1/5) Code Example: Product – Bean Class … // Not to locate the record, but to verify that the record exists public String ejbFindByPrimaryKey(String primaryKey) throws FinderException { boolean result; try { result = selectByPrimaryKey(primaryKey) } catch (Exception e) { } if (result) return primaryKey; else throw new ObjectNotFoundException(“Row for ” + primaryKey + “ not found”); } …
50
Example EJB Programming [21/25] BMP Entity Bean (2/5) Code Example: Product – Bean Class … public boolean selectByPrimaryKey(String primaryKey) throws SQLException { String selectStmt = “select productId ” + “from product where productId = ?”; PreparedStatement prepStmt = _conn.prepareStatement(selectStmt); prepStmt.setString(1, primaryKey); ResultSet rs = prepStmt.executeQuery(); boolean result = rs.next(); prepStmt.close(); return result; } …
51
Example EJB Programming [22/25] BMP Entity Bean (3/5) Code Example: Product – Bean Class public void ejbLoad() { try { loadRow(); } catch (Exception e) { } } Private void loadRow() throws SQLException { String selectStmt = “select description, price ” + “from product where productId = ?”; PreparedStatement prepStmt = _conn.prepareStatement(selectStmt); prepStmt.setString(1, this.productId); ResultSet rs = prepStmt.executeQuery(); if (rs.next()) { this.description = rs.getString(1); this.price = rs.getDouble(2); } else throw new NoSuchEntityException(“Row for ” + productId + “not found”); }
52
Example EJB Programming [23/25] BMP Entity Bean (4/5) Code Example: Product – Bean Class public Collection ejbFindByPriceRange(double low, double high) throws FinderException { try { result = selectByPriceRange(low, high); } catch (Exception e) { } if (result.isEmpty()) throw new ObjectNotFoundException(“No rows found”); else return result; }
53
Example EJB Programming [24/25] BMP Entity Bean (5/5) Code Example: Product – Bean Class public Collection selectByPriceRange(double low, double high) throws SQLException { String selectStmt = “select productId from product ” + “where price >= low and price <= high”; PreparedStatement prepStmt = _conn.prepareStatement(selectStmt); prepStmt.setDouble(1, low); prepStmt.setDouble(2, high); ResultSet rs = prepStmt.executeQuery(); ArrayList a = new ArrayList(); while (rs.next()) { String productId = rs.getString(1); a.add(productId); } prepStmt.close(); return a; }
54
EJB Programming [25/25] Entity Bean Lifecycle Does not exist Ready Pooled newInstance() setEntityContext() unset- EntityContext() ejbRemove() or ejbPassivate() ejbCreate() or ejbActivate() ejbLoad() business method ejbStore()
55
Outline Java EE EJB Overview Enterprise Beans EJB Programming Changes in EJB 3.0 References
56
EJB 2.1 technology very powerful, but too complex Too many classes, interfaces Boilerplate javax.ejb interface methods Clumsy programming model Deployment descriptors EJB 3.0 Goals Make EJB easier to learn and use Improve developer productivity Attract broader range of developers Changes in EJB 3.0 [1/3] Motivation
57
Simplification of the EJB APIs Removal of need for EJBHome and EJBObject Removal of JNDI APIs from developer and client view Removal of need for deployment descriptors Use advantages of Java language metadata Metadata designed so that the most common cases are easiest to express Defaults available for expected cases More work is done by container, less by developer Changes in EJB 3.0 [2/3] EJB 3.0 Approach
58
Example Enterprise Bean [3/3] Stateful Session Bean (1/4) Code Example: Shopping Cart – Bean Class @stateful public class CartBean implements Cart { public int addItem(int item) { … } public void purchase() { … } … @PreDestroy remove() { … } } public interface Cart { public int addItem(int item); public void purchase(); } No Home interface Deployment descriptor annotations
59
Outline Java EE EJB Overview Enterprise Beans EJB Programming Changes in EJB 3.0 References
60
References EJB 프로그래밍 입문 http://www.javastudy.co.kr/docs/lec_ejb/ejb/sunny_ejb1.pdf Jboss – open source http://labs.jboss.com/ http://sourceforge.net/projects/jbosshttp://sourceforge.net/projects/jboss (download)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.