SlideShare a Scribd company logo
Example:
           Stateless Session Bean




The Home Interface

import javax.ejb.*;
import java.rmi.RemoteException;

public interface HelloHome extends EJBHome {
  Hello create() throws RemoteException,
  CreateException;
}
The Remote Interface

import javax.ejb.*;
import java.rmi.RemoteException;
import java.rmi.Remote;

public interface Hello extends EJBObject {
  public String hello() throws
             java.rmi.RemoteException;
}




The Bean Class

public class HelloBean implements SessionBean {
  // these are required session bean methods
  public void ejbCreate() {}
  public void ejbRemove() {}
  public void ejbActivate() {}
  public void ejbPassivate() {}
  public void setSessionContext(SessionContext ctx) {}

    // this is our business method to be called by the client
    public String hello() {
           return “Hello, world!”;
    }
}
Session Bean Required Methods
     The following methods are defined in the SessionBean
     interface:
     void ejbCreate(…init params…)
            Performs necessary initializations when an instance is created
     void ejbRemove()
            Prepare for the bean’s destruction
     void ejbActivate()
            Prepare needed resources to return from hibernation
     void ejbPassivate()
            Releases any resources (database connections, files) before an
            instance is put into hibernation
     void setSessionContext(SessionContext sc)
            Stores the session context (used for communicating with the EJB
            container)




The EJB Client

public class HelloClient {
  public static void main(String[] args) {
    try {
       InitialContext ic = new InitialContext();
       Object objRef = ic.lookup("java:comp/env/ejb/Hello");
       HelloHome home =
    (HelloHome)PortableRemoteObject.narrow(
                   objRef, HelloHome.class);
       Hello hello = home.create();
       System.out.println( hello.hello() );
       hello.remove();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Example:
                 Stateful Session Bean




The Home Interface

import javax.ejb.*;
import java.rmi.RemoteException;

public interface CountHome extends EJBHome {
  Count create() throws RemoteException,
  CreateException;
}
The Remote Interface

import javax.ejb.*;
import java.rmi.RemoteException;
import java.rmi.Remote;

public interface Count extends EJBObject {
  public int count() throws
            java.rmi.RemoteException;
}




The Bean Class

public class CountBean implements SessionBean {
  private int val = 0;

    public void ejbCreate() {}
    public void ejbRemove() {}
    public void ejbActivate() {}
    public void ejbPassivate() {}
    public void setSessionContext(SessionContext ctx) {}

    // this is our business method to be called by the client
    public int count() {
           return ++val;
    }
}
The EJB Client
public class CountClient {
  public static void main(String[] args) {
    try {
       InitialContext ic = new InitialContext();
      Object objRef = ic.lookup("java:comp/env/ejb/Count");
      CountHome home = (CountHome)
          PortableRemoteObject.narrow(objRef, CountHome.class);
       Count count = home.create();
       System.out.println(“Count:”+count.count() );
       System.out.println(“Count:”+count.count() );
       System.out.println(“Count:”+count.count() );
       count.remove();
    } catch (Exception e) {}
  }
}




                   Entity Beans
What Are Entity Beans?

 They represent data elements
 Unlike session beans, entity beans last longer
 than a client session
    Entity beans last as long as the data they represent
    lasts
 In reality, entity beans are a data access wrapper
 (e.g. database encapsulation)
    When entity bean’s data is modified, so is the
    representative data in the database (& vice versa)
    Whether this is done by the container, or explicitly by
    the programmer, depends on what kinds of Entity
    bean it is




Entity Bean Data Mappings


  Entity Bean             pkField   SomeField   …    …
                          1         …           …    …
   Entity Bean
                          2         …           …    …
                          3         …           …    …
 Entity Bean


   Entity Bean
Entity Bean Facts
 The persistent data represented by the entity bean is
 stored safely
    Usually in a database
    Entity beans keep their data even after a crash
 Multiple entity beans can represent the same data in the
 database
    Used for handling multiple clients who want to access the same
    data
 Entity beans can be re-used
    Entity beans of a given type may be placed into a pool and
    reused for different clients
    The data the entity beans represent will change




             Example:
             Entity Beans
             Container-Managed Persistence (CMP)
The Home Interface
   import javax.ejb.*;
   import java.rmi.RemoteException;
   import java.util.*;

   public interface AccountHome extends EJBHome {
     public Account create(Integer accountID, String owner)
            throws RemoteException, CreateException;
     public Account findByPrimaryKey(Integer accountID)
            throws FinderException, RemoteException;
   }




 The Remote Interface

import javax.ejb.*;
import java.rmi.*;

public interface Account extends EJBObject {
  public void deposit(double amount) throws RemoteException;
  public void withdraw(double amount) throws RemoteException;
  public double getBalance() throws RemoteException;
}
The Bean Class
import javax.ejb.*;
import java.rmi.*;
import java.util.*;

public abstract class AccountBean implements EntityBean {

public abstract void setAccountID(Integer accountID);
public abstract Integer getAccountID();
public abstract void setBalance(double balance);
public abstract bouble setBalance();
public abstract void setOwnerName(String ownerName);
public abstract String getOwnerName();

     public Integer ejbCreate(int accountID, String owner) throws CreateException {
     setAccountID(accountID);
     setOwnerName(owner);
     return new Integer(0);
     }

     public void ejbPostCreate(int accountID, String owner) {}
     public void ejbRemove() {}
     public void ejbActivate() {}
     public void ejbPassivate() {}
     public void ejbLoad() {}
     public void ejbStore() {}
     public void setEntityContext(EntityContext ctx) {}
     public void setEntityContext() {}




       The Bean Class (contd.)

                public void withdraw(double amount)
                {
                    setBalance( getBalance() - amount );
                }

                public void deposit(double amount)
                {
                    setBalance( getBalance() + amount );
                }
          }
The EJB Client

public class AccountClient {
  public static void main(String[] args) {
    try {
      Context ctx = new InitialContext();
      Object ref = ctx.lookup(“java:comp/env/ejb/Account”);
       AccountHome home = (AccountHome)
       PortableRemoteObject.narrow(objRef, AccountHome.class);
      Account newAccount = home.create(123, “John Smith”);
      newAccount.deposit(100);
      newAccount.remove();
      Collection accounts = home.findByOwnerName(“John Smith”);
    } catch (Exception e) {}
  }
}




                  Enterprise
                  Applications
J2EE application model
J2EE is a multitiered distributed application model
  client machines
  the J2EE server machine
  the database or legacy machines at the back end




                    Resource Pooling
Database Connection Pooling

  Connection pooling is a technique
                                                     RDBMS
that was pioneered by database
vendors to allow multiple clients to
share a cached set of connection
objects that provide access to a
database resource
                                                     Connection
  Connection pools minimize the                         Pool
opening and closing of connections


                                                      Servlet



                                          Client 1      ……        Client n




References
  Developing Enterprise Applications Using the J2EE Platform,
  http://java.sun.com/developer/onlineTraining/J2EE/Intro2/j2ee.html

More Related Content

PPT
PDF
EJB et WS (Montreal JUG - 12 mai 2011)
PPT
Hibernate
PDF
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
PPT
Intorduction of Playframework
PPT
Jsp/Servlet
PDF
Mastering Oracle ADF Bindings
PDF
Commons Pool and DBCP
EJB et WS (Montreal JUG - 12 mai 2011)
Hibernate
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
Intorduction of Playframework
Jsp/Servlet
Mastering Oracle ADF Bindings
Commons Pool and DBCP

What's hot (20)

PDF
Spring 4 - A&BP CC
PDF
Hidden rocks in Oracle ADF
PDF
Advanced java practical semester 6_computer science
PPT
JavaScript
PDF
Web2py tutorial to create db driven application.
PDF
Design how your objects talk through mocking
PDF
Lecture 3: Servlets - Session Management
PDF
Decoupling with Design Patterns and Symfony2 DIC
PDF
Deep dive into Oracle ADF
PPT
PPT
Play!ng with scala
PDF
Sane Async Patterns
PDF
50 new features of Java EE 7 in 50 minutes
PDF
Min-Maxing Software Costs - Laracon EU 2015
PDF
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
PDF
Drupal 8: Fields reborn
PPT
Developing application for Windows Phone 7 in TDD
PPTX
Test and profile your Windows Phone 8 App
PDF
Web注入+http漏洞等描述
PPTX
Solid Software Design Principles
Spring 4 - A&BP CC
Hidden rocks in Oracle ADF
Advanced java practical semester 6_computer science
JavaScript
Web2py tutorial to create db driven application.
Design how your objects talk through mocking
Lecture 3: Servlets - Session Management
Decoupling with Design Patterns and Symfony2 DIC
Deep dive into Oracle ADF
Play!ng with scala
Sane Async Patterns
50 new features of Java EE 7 in 50 minutes
Min-Maxing Software Costs - Laracon EU 2015
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
Drupal 8: Fields reborn
Developing application for Windows Phone 7 in TDD
Test and profile your Windows Phone 8 App
Web注入+http漏洞等描述
Solid Software Design Principles
Ad

Viewers also liked (20)

DOCX
CUBITOS PARA JUGAR
KEY
Furnished apartment projec
PPT
Avoiding Work at Home Scams
PDF
Intervento dell'ASL del VCO Convegno Acqua Premia
PPT
Final data collection webinar highlights & reminders
PDF
Cv Wow Media Pack
PDF
How To Surround Yourself with the Right People
PPT
The Vineyards Hotel Spa and iMA Training complex (iMAplex)
PPTX
день знаний семьи анисимовых
DOC
Luan van phat trien nguon nhan luc1
ODP
#weightloss 2014 vs Old School #Dieting
PPTX
клепа2011,альманах
PDF
The Millennial Shift: Financial Services and the Digial Generation Study Preview
PDF
5 Steps for Better Machine Translation Quality - Infographic
PPT
Adknowledge Publishers Uk
PDF
6 quan ly-tien_trinh
PPTX
The process of the making of my music magazine
PDF
Step by step guidance general overview final_new
PPTX
Strategic management
CUBITOS PARA JUGAR
Furnished apartment projec
Avoiding Work at Home Scams
Intervento dell'ASL del VCO Convegno Acqua Premia
Final data collection webinar highlights & reminders
Cv Wow Media Pack
How To Surround Yourself with the Right People
The Vineyards Hotel Spa and iMA Training complex (iMAplex)
день знаний семьи анисимовых
Luan van phat trien nguon nhan luc1
#weightloss 2014 vs Old School #Dieting
клепа2011,альманах
The Millennial Shift: Financial Services and the Digial Generation Study Preview
5 Steps for Better Machine Translation Quality - Infographic
Adknowledge Publishers Uk
6 quan ly-tien_trinh
The process of the making of my music magazine
Step by step guidance general overview final_new
Strategic management
Ad

Similar to Ejb examples (20)

PPT
EJB Clients
PPTX
Skillwise EJB3.0 training
PDF
Ejb3 Dan Hinojosa
PPT
2 introduction toentitybeans
PPT
Ejb 2.0
PPT
CommercialSystemsBahman.ppt
PDF
softshake 2014 - Java EE
PDF
Local data storage for mobile apps
DOCX
Ecom lec4 fall16_jpa
PDF
Silicon Valley JUG: JVM Mechanics
PDF
What's New in Enterprise JavaBean Technology ?
PDF
Enterprise Guice 20090217 Bejug
PDF
What's new and noteworthy in Java EE 8?
PDF
Play 2.0
PPT
比XML更好用的Java Annotation
PPT
Session 3 Tp3
PPT
EJB 3.0 Java Persistence with Oracle TopLink
PDF
Singletons in PHP - Why they are bad and how you can eliminate them from your...
PDF
Local storage in Web apps
PPT
J2 Ee Overview
EJB Clients
Skillwise EJB3.0 training
Ejb3 Dan Hinojosa
2 introduction toentitybeans
Ejb 2.0
CommercialSystemsBahman.ppt
softshake 2014 - Java EE
Local data storage for mobile apps
Ecom lec4 fall16_jpa
Silicon Valley JUG: JVM Mechanics
What's New in Enterprise JavaBean Technology ?
Enterprise Guice 20090217 Bejug
What's new and noteworthy in Java EE 8?
Play 2.0
比XML更好用的Java Annotation
Session 3 Tp3
EJB 3.0 Java Persistence with Oracle TopLink
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Local storage in Web apps
J2 Ee Overview

More from vantinhkhuc (20)

PDF
Url programming
PDF
Servlets intro
PDF
Servlet sessions
PDF
Security overview
PDF
PDF
PDF
Lecture17
PDF
Lecture11 b
PDF
Lecture10
PDF
Lecture9
PDF
Lecture6
PDF
PDF
Jsf intro
PDF
Jsp examples
PDF
PDF
PDF
PDF
Ejb intro
PPT
Chc6b0c6a1ng 12
PPT
Url programming
Servlets intro
Servlet sessions
Security overview
Lecture17
Lecture11 b
Lecture10
Lecture9
Lecture6
Jsf intro
Jsp examples
Ejb intro
Chc6b0c6a1ng 12

Ejb examples

  • 1. Example: Stateless Session Bean The Home Interface import javax.ejb.*; import java.rmi.RemoteException; public interface HelloHome extends EJBHome { Hello create() throws RemoteException, CreateException; }
  • 2. The Remote Interface import javax.ejb.*; import java.rmi.RemoteException; import java.rmi.Remote; public interface Hello extends EJBObject { public String hello() throws java.rmi.RemoteException; } The Bean Class public class HelloBean implements SessionBean { // these are required session bean methods public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext ctx) {} // this is our business method to be called by the client public String hello() { return “Hello, world!”; } }
  • 3. Session Bean Required Methods The following methods are defined in the SessionBean interface: void ejbCreate(…init params…) Performs necessary initializations when an instance is created void ejbRemove() Prepare for the bean’s destruction void ejbActivate() Prepare needed resources to return from hibernation void ejbPassivate() Releases any resources (database connections, files) before an instance is put into hibernation void setSessionContext(SessionContext sc) Stores the session context (used for communicating with the EJB container) The EJB Client public class HelloClient { public static void main(String[] args) { try { InitialContext ic = new InitialContext(); Object objRef = ic.lookup("java:comp/env/ejb/Hello"); HelloHome home = (HelloHome)PortableRemoteObject.narrow( objRef, HelloHome.class); Hello hello = home.create(); System.out.println( hello.hello() ); hello.remove(); } catch (Exception e) { e.printStackTrace(); } } }
  • 4. Example: Stateful Session Bean The Home Interface import javax.ejb.*; import java.rmi.RemoteException; public interface CountHome extends EJBHome { Count create() throws RemoteException, CreateException; }
  • 5. The Remote Interface import javax.ejb.*; import java.rmi.RemoteException; import java.rmi.Remote; public interface Count extends EJBObject { public int count() throws java.rmi.RemoteException; } The Bean Class public class CountBean implements SessionBean { private int val = 0; public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext ctx) {} // this is our business method to be called by the client public int count() { return ++val; } }
  • 6. The EJB Client public class CountClient { public static void main(String[] args) { try { InitialContext ic = new InitialContext(); Object objRef = ic.lookup("java:comp/env/ejb/Count"); CountHome home = (CountHome) PortableRemoteObject.narrow(objRef, CountHome.class); Count count = home.create(); System.out.println(“Count:”+count.count() ); System.out.println(“Count:”+count.count() ); System.out.println(“Count:”+count.count() ); count.remove(); } catch (Exception e) {} } } Entity Beans
  • 7. What Are Entity Beans? They represent data elements Unlike session beans, entity beans last longer than a client session Entity beans last as long as the data they represent lasts In reality, entity beans are a data access wrapper (e.g. database encapsulation) When entity bean’s data is modified, so is the representative data in the database (& vice versa) Whether this is done by the container, or explicitly by the programmer, depends on what kinds of Entity bean it is Entity Bean Data Mappings Entity Bean pkField SomeField … … 1 … … … Entity Bean 2 … … … 3 … … … Entity Bean Entity Bean
  • 8. Entity Bean Facts The persistent data represented by the entity bean is stored safely Usually in a database Entity beans keep their data even after a crash Multiple entity beans can represent the same data in the database Used for handling multiple clients who want to access the same data Entity beans can be re-used Entity beans of a given type may be placed into a pool and reused for different clients The data the entity beans represent will change Example: Entity Beans Container-Managed Persistence (CMP)
  • 9. The Home Interface import javax.ejb.*; import java.rmi.RemoteException; import java.util.*; public interface AccountHome extends EJBHome { public Account create(Integer accountID, String owner) throws RemoteException, CreateException; public Account findByPrimaryKey(Integer accountID) throws FinderException, RemoteException; } The Remote Interface import javax.ejb.*; import java.rmi.*; public interface Account extends EJBObject { public void deposit(double amount) throws RemoteException; public void withdraw(double amount) throws RemoteException; public double getBalance() throws RemoteException; }
  • 10. The Bean Class import javax.ejb.*; import java.rmi.*; import java.util.*; public abstract class AccountBean implements EntityBean { public abstract void setAccountID(Integer accountID); public abstract Integer getAccountID(); public abstract void setBalance(double balance); public abstract bouble setBalance(); public abstract void setOwnerName(String ownerName); public abstract String getOwnerName(); public Integer ejbCreate(int accountID, String owner) throws CreateException { setAccountID(accountID); setOwnerName(owner); return new Integer(0); } public void ejbPostCreate(int accountID, String owner) {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void ejbLoad() {} public void ejbStore() {} public void setEntityContext(EntityContext ctx) {} public void setEntityContext() {} The Bean Class (contd.) public void withdraw(double amount) { setBalance( getBalance() - amount ); } public void deposit(double amount) { setBalance( getBalance() + amount ); } }
  • 11. The EJB Client public class AccountClient { public static void main(String[] args) { try { Context ctx = new InitialContext(); Object ref = ctx.lookup(“java:comp/env/ejb/Account”); AccountHome home = (AccountHome) PortableRemoteObject.narrow(objRef, AccountHome.class); Account newAccount = home.create(123, “John Smith”); newAccount.deposit(100); newAccount.remove(); Collection accounts = home.findByOwnerName(“John Smith”); } catch (Exception e) {} } } Enterprise Applications
  • 12. J2EE application model J2EE is a multitiered distributed application model client machines the J2EE server machine the database or legacy machines at the back end Resource Pooling
  • 13. Database Connection Pooling Connection pooling is a technique RDBMS that was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provide access to a database resource Connection Connection pools minimize the Pool opening and closing of connections Servlet Client 1 …… Client n References Developing Enterprise Applications Using the J2EE Platform, http://java.sun.com/developer/onlineTraining/J2EE/Intro2/j2ee.html