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

What's hot

Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
JWORKS powered by Ordina
 
Hidden rocks in Oracle ADF
Hidden rocks in Oracle ADFHidden rocks in Oracle ADF
Hidden rocks in Oracle ADF
Euegene Fedorenko
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
Niraj Bharambe
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.Web2py tutorial to create db driven application.
Web2py tutorial to create db driven application.
fRui Apps
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
Konstantin Kudryashov
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
Fahad Golra
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
Konstantin Kudryashov
 
Deep dive into Oracle ADF
Deep dive into Oracle ADFDeep dive into Oracle ADF
Deep dive into Oracle ADF
Euegene Fedorenko
 
Jquery
JqueryJquery
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
Siarzh Miadzvedzeu
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
TrevorBurnham
 
50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes50 new features of Java EE 7 in 50 minutes
50 new features of Java EE 7 in 50 minutes
Antonio Goncalves
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
Konstantin Kudryashov
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Drupal 8: Fields reborn
Drupal 8: Fields rebornDrupal 8: Fields reborn
Drupal 8: Fields reborn
Pablo López Escobés
 
Developing application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDDDeveloping application for Windows Phone 7 in TDD
Developing application for Windows Phone 7 in TDD
Michele Capra
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
Michele Capra
 
Web注入+http漏洞等描述
Web注入+http漏洞等描述Web注入+http漏洞等描述
Web注入+http漏洞等描述
fangjiafu
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
Jon Kruger
 

What's hot (20)

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

Viewers also liked

CUBITOS PARA JUGAR
CUBITOS PARA JUGARCUBITOS PARA JUGAR
CUBITOS PARA JUGAR
ÄLËJÄNDRÖ Sänmïgüël
 
Furnished apartment projec
Furnished apartment projecFurnished apartment projec
Furnished apartment projecambersweet95
 
Avoiding Work at Home Scams
Avoiding Work at Home ScamsAvoiding Work at Home Scams
Avoiding Work at Home Scams
graspitmarketing
 
Intervento dell'ASL del VCO Convegno Acqua Premia
Intervento dell'ASL del VCO Convegno Acqua PremiaIntervento dell'ASL del VCO Convegno Acqua Premia
Intervento dell'ASL del VCO Convegno Acqua Premia
Massimo Falsaci
 
Final data collection webinar highlights & reminders
Final   data collection webinar highlights  & remindersFinal   data collection webinar highlights  & reminders
Final data collection webinar highlights & reminders
progroup
 
Cv Wow Media Pack
Cv Wow Media PackCv Wow Media Pack
Cv Wow Media Pack
Darren Roach
 
How To Surround Yourself with the Right People
How To Surround Yourself with the Right PeopleHow To Surround Yourself with the Right People
How To Surround Yourself with the Right People
Susie Pan
 
The Vineyards Hotel Spa and iMA Training complex (iMAplex)
The Vineyards Hotel Spa and iMA Training complex (iMAplex)The Vineyards Hotel Spa and iMA Training complex (iMAplex)
The Vineyards Hotel Spa and iMA Training complex (iMAplex)
James Knight
 
Hair
HairHair
день знаний семьи анисимовых
день знаний семьи анисимовыхдень знаний семьи анисимовых
день знаний семьи анисимовых
klepa.ru
 
Luan van phat trien nguon nhan luc1
Luan van phat trien nguon nhan luc1Luan van phat trien nguon nhan luc1
Luan van phat trien nguon nhan luc1nguyenthivan2803
 
#weightloss 2014 vs Old School #Dieting
#weightloss 2014 vs Old School #Dieting#weightloss 2014 vs Old School #Dieting
#weightloss 2014 vs Old School #Dieting
Cindy McAsey
 
клепа2011,альманах
клепа2011,альманахклепа2011,альманах
клепа2011,альманах
klepa.ru
 
The Millennial Shift: Financial Services and the Digial Generation Study Preview
The Millennial Shift: Financial Services and the Digial Generation Study PreviewThe Millennial Shift: Financial Services and the Digial Generation Study Preview
The Millennial Shift: Financial Services and the Digial Generation Study Preview
Corporate Insight
 
5 Steps for Better Machine Translation Quality - Infographic
5 Steps for Better Machine Translation Quality - Infographic5 Steps for Better Machine Translation Quality - Infographic
5 Steps for Better Machine Translation Quality - Infographic
Multilizer
 
Adknowledge Publishers Uk
Adknowledge Publishers UkAdknowledge Publishers Uk
Adknowledge Publishers Uk
thelongertail
 
6 quan ly-tien_trinh
6 quan ly-tien_trinh6 quan ly-tien_trinh
6 quan ly-tien_trinhvantinhkhuc
 
The process of the making of my music magazine
The process of the making of my music magazineThe process of the making of my music magazine
The process of the making of my music magazine
ozgealtinok
 
Step by step guidance general overview final_new
Step by step guidance general overview final_newStep by step guidance general overview final_new
Step by step guidance general overview final_new
eTwinning Europe
 
Strategic management
Strategic managementStrategic management
Strategic management
Jasleen Kaur
 

Viewers also liked (20)

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

Similar to Ejb examples

EJB Clients
EJB ClientsEJB Clients
EJB Clients
Roy Antony Arnold G
 
Skillwise EJB3.0 training
Skillwise EJB3.0 trainingSkillwise EJB3.0 training
Skillwise EJB3.0 training
Skillwise Group
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
Dan Hinojosa
 
2 introduction toentitybeans
2 introduction toentitybeans2 introduction toentitybeans
2 introduction toentitybeans
ashishkirpan
 
Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0
sukace
 
CommercialSystemsBahman.ppt
CommercialSystemsBahman.pptCommercialSystemsBahman.ppt
CommercialSystemsBahman.ppt
KalsoomTahir2
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
Alexis Hassler
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
Ivano Malavolta
 
Ecom lec4 fall16_jpa
Ecom lec4 fall16_jpaEcom lec4 fall16_jpa
Ecom lec4 fall16_jpa
Zainab Khallouf
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
What's New in Enterprise JavaBean Technology ?
What's New in Enterprise JavaBean Technology ?What's New in Enterprise JavaBean Technology ?
What's New in Enterprise JavaBean Technology ?
Sanjeeb Sahoo
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
robbiev
 
What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?What's new and noteworthy in Java EE 8?
What's new and noteworthy in Java EE 8?
gedoplan
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
elizhender
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Session 3 Tp3
Session 3 Tp3Session 3 Tp3
Session 3 Tp3
phanleson
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
Bill Lyons
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
go_oh
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
Ivano Malavolta
 
J2 Ee Overview
J2 Ee OverviewJ2 Ee Overview
J2 Ee Overview
Atul Shridhar
 

Similar to Ejb examples (20)

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

More from vantinhkhuc

Url programming
Url programmingUrl programming
Url programming
vantinhkhuc
 
Servlets intro
Servlets introServlets intro
Servlets intro
vantinhkhuc
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
vantinhkhuc
 
Security overview
Security overviewSecurity overview
Security overview
vantinhkhuc
 
Rmi
RmiRmi
Lecture17
Lecture17Lecture17
Lecture17
vantinhkhuc
 
Lecture11 b
Lecture11 bLecture11 b
Lecture11 b
vantinhkhuc
 
Lecture10
Lecture10Lecture10
Lecture10
vantinhkhuc
 
Lecture9
Lecture9Lecture9
Lecture9
vantinhkhuc
 
Lecture6
Lecture6Lecture6
Lecture6
vantinhkhuc
 
Jsse
JsseJsse
Jsf intro
Jsf introJsf intro
Jsf intro
vantinhkhuc
 
Jsp examples
Jsp examplesJsp examples
Jsp examples
vantinhkhuc
 
Jpa
JpaJpa
Corba
CorbaCorba
Ajax
AjaxAjax
Ejb intro
Ejb introEjb intro
Ejb intro
vantinhkhuc
 

More from vantinhkhuc (20)

Url programming
Url programmingUrl programming
Url programming
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Security overview
Security overviewSecurity overview
Security overview
 
Rmi
RmiRmi
Rmi
 
Md5
Md5Md5
Md5
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture11 b
Lecture11 bLecture11 b
Lecture11 b
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture9
Lecture9Lecture9
Lecture9
 
Lecture6
Lecture6Lecture6
Lecture6
 
Jsse
JsseJsse
Jsse
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Jsp examples
Jsp examplesJsp examples
Jsp examples
 
Jpa
JpaJpa
Jpa
 
Corba
CorbaCorba
Corba
 
Ajax
AjaxAjax
Ajax
 
Ejb intro
Ejb introEjb intro
Ejb intro
 
Chc6b0c6a1ng 12
Chc6b0c6a1ng 12Chc6b0c6a1ng 12
Chc6b0c6a1ng 12
 
Ch06
Ch06Ch06
Ch06
 

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