Enterprise Java beans

by Sandeep Desai (http://www.thedesai.net/sandeep)

 

Book Reference:

 

Mock exams

 

Certification to Spec mapping

http://www.valoxo.ch/jr/cheatsheets.html

 

Sample created with JDeveloper works against Oracle 10.2 Database scott schema

Contains MySessionEJBClient which is a sample client

 

EJB, Write Once Deploy anywhere (WODA)

 

EJB Container

 

Container intercepts client requests and inserts security, transaction and persistence

 

Bean types

 

RMI (Remote Method invocation)

 

 

bean methods exposed through component interface

client does not access bean directly, it accesses EJBObject via EJBHome

fetch EJBHome using JNDI lookup

 

security on method by method basis

Beans should not create threads

 

Client code

 

import javax.naming.*;

import java.rmi.*;

import javax.rmi.*;

import javax.ejb.*;

 

public class MyClient {

  public static void main(String[] args) {

     foo(false); // statless

     foo(true);  // stateful

  }

  public void foo(boolean state)

    try {

      Context ic = new InitialContext();

      Object o = ic.lookup("Advisor");

      AdviceHome home = (AdviceHome) PortableRemoteObject.narrow(o, AdviceHome.class);

      Advice advisor = null;

      if (!state)

         advisor = home.create();

      else advisor = home.create("boston");

      System.out.println(advisor.getAdvice());

       if (state) advisor.remove();

   } catch (RemoteException rex) { rex.printStackTrace(); }

     catch (CreateException cex) { cex.printStackTrace(); }

     catch (Exception cex) { ex.printStackTrace(); }

}

 

 

// Server side home interface

// Stateless session beans can have only one no arg create()

// Stateful session beans can have multiple overloaded create()

// Stateful Session Beans parameters musts be RMI-IIOP compatible (primitive, serializable, array, collections)

// create method names for stateful beans must start with create e.g createAccount()

 

import javax.ejb.*;

import java.rmi.RemoteException;

 

public interface AdviceHome extends EJBHome {

  public Advice create() throws CreateException, RemoteException

}

 

interface Remote

 

interface EJBHome extends Remote

  EJBMetaData getEJBMetaData() // get reflection like info about the bean, call getHomeInterfaceClass(), getPrimaryKeyClass(), isSession() on EJBMetaData

  HomeHandle getHomeHandle() // serialize home, so you can use home without JNDI lookup

  void removeHandle(Handle h) throws RemoveException  // pass EJB object's handle and tell home that session bean is done

  void remove(Object primaryKey) throws RemoveException // delete entity bean from persistent store, delete row from database, takes primary key, we never remove Home

 

interface HomeHandle extends Serializable

  EJBHome getEJBHome()

 

interface EJBObject extends Remote

  Object getPrimaryKey() // calling on Session bean throws RemoteException or EJBException

  EJBHome getEJBHome() 

  Handle getHandle() // use handle to get back to EJBObject how ?

  void remove()throws RemoveException // tell session bean we are done

  boolean isIdentical(EJBObject o) // stateless always true, stateful always false, entity bean true if same primary key

 

interface Handle extends Serializable

  EJBObject getEJBObject() // call PortableRemoteObject.narrow(o, foo.class)  on return object, can return RemoteException if bean does not exist (e.g session bean destroyed after timeout)

 

Component interface is interface that extends EJBObject

Expose business methods here

 

import javax.ejb.*;

import java.rmi.RemoteException;

 

// arguments should RMI-IIOP compatible

// can have overloaded methods

// each method should declare RemoteException

// Methods cannot throw RuntimeExceptions, can throw other Exception

public interface Advice extends EJBObject {

   public String getAdvice() throws RemoteException

}

 

Local interface do not extend Remote, cannot mix local and remote

 

EJBLocalHome

  // use reflection for getEJBMetaData type information

  void remove(Object primaryKey)

 

EJBLocalObject

  Object getPrimaryKey() // calling on Session bean throws RemoteException or EJBException

  EJBLocalHome getEJBLocalHome() 

  void remove() // tell session bean we are done

  boolean isIdentical(EJBLocalObject o) // stateless always true, stateful always false, entity

 

 

 

Writing local Client interface

 

// Component interface

import javax.ejb.*;

 

public interface AdviceLocal extends EJBLocalObject {

  public String getAdvice();

}

 

// Home interface

 

import javax.ejb.*;

 

public interface AdviceHomeLocal extends EJBLocalHome {

  public AdviceLocal create() throws CreateException;

}

 

 

 

Exceptions

 

All exceptions are in javax.ejb.*

EJBException Runtime exception

 

 

Remote Client View

Local Client View

All methods

RemoteException

EJBException

CREATE methods

RemoteException

CreateException

EJBException

CreateException

REMOVE methods

RemoteException

RemoveException

EJBException

RemoveException

 

If Bean called by local client then object passed by reference and bean could modify, if object passed Remotely then it is a copy

 

Local vs Remote is a coding time decision, we cannot create client code that works both way. Also bean should make clone of arguments and clone of return value if it is being called locally. This way it is sure that nobody will modify object

 

 

Local Client Code

 

 

import javax.naming.*;

import javax.ejb.*;

 

public class AdviceLocalClient {

   public static void main(String[] args) {

      Object o = null;

      try {  Context ic = new InitialContext(); o = ic.lookup("AdvisorLocal"); }

      catch (NamingException nex) {}

      AdviceHomeLocal home = (AdviceHomeLocal) o; // no narrow for local

      try {  AdviceLocal advisor = home.create(); System.out.println(advisor.getAdvice();

      catch (CreateException cex) {}

  }

}

 

 

Exam watch: Differentiate client/remote view problems, non serializable parameters on remote, calling handle API on local, not checking RemoteException etc

 

 

 

 

 

 

 

 

 

 

Bean lifecycle

 

Stateful session beans

 

Bean creation (client request)

Bean use (client calls business method)

Bean passivation (put to sleep)

Bean activation

Bean removal (client finished or timeout)

 

Stateless session beans

Bean creation (container creates bean)

Bean use

Bean removal (container removes if too many beans in pool)

 

 

interface SessionBean

setSessionContext(SessionContext sc) throws EJBException, RemoteException

ejbActivate() throws EJBException, RemoteException

ejbPassivate() throws EJBException, RemoteException

ejbRemove() throws EJBException, RemoteException

 

 

 

 

import javax.rmi.RemoteException;

import javax.ejb.*;

// LocalHome return Local interface, Remote Home returns Remote component interface

public interface AdviceHome extends EJBHome {

   // must have CreateException

   public Advice create(String clientName) throws CreateException, RemoteException

}

 

import javax.ejb.*;

 

class AdviceBean implements SessionBean {

  private SessionContext context;

  private String name;

 

  // public AdviceBean() {} // no constructor

 

   // can access home here, access special JNDI context

 

   public void setSessionContext(SessionContext ctx) {

      context = ctx;     }

 

 

    // for passivate and activate, create and remove

    // can use SessionContext to access home, EJB Object and client security information

  // get transaction reference and call methods on it (BMT beans)

   // access special JNDI environment, another beans methods, resource manager

 

   // create must match create in Home interface

   // init code goes here

   // no args constructor stateless bean

   public void ejbCreate() { }

 

  // stateful beans args constructor

   // stateful or stateless decided at deploy time

   public void ejbCreate(String clientName) { name = clientName; }

 

      // after ejbPassivate completes, every non transient instance variable must be reference to one of following

    //  serializable object, null,

   // beans remote component or home interface, local  component or home interface

// sessioncontext, special JNDI context or subcontext

// UserTransaction, resource Manager (e.g javax.sql.DataSource)

 

// stateful session bean not passivated while in transaction  

 

   public void ejbPassivate() { connection = null;  cleanup(); }

    public void  ejbActivate() {  try { connection = myDataSource.getConnection(); } catch (Exception e) {}

    // if transient variables are used, reset to default here (passivation does not set default, serialization does)

}

 

   // client calls remove, bean times out, bean throws system exception

    // not called if  beans in passive state

   // not called on server crash

    // if deleting row from database here, note that you may end up with orphans as ejbRemove not called, upto user to cleanup periodically

   public void ejbRemove() {  cleanup(); }

 

   // Not part of spec, but recommended best practice

   public void cleanup() {  resource.close(); }

 

   // get home, EJB Object, client security info

   // check or force transaction rollback (CMT), get transaction reference (BMT Beans)

   // access special JNDI context, another beans methods, resource manager

   public void fooBusinessMethod() {}

 

   Object connection; 

   String name;

}

 

Stateful Session Bean lifecycle and callbacks

 

[does not exist state]:   called on time out, system exception or ejbRemove

            // below done once only

create Bean with constructor // don't call EJB APIs here

setSessionContext()

ejbCreate()

goto [method ready state]

 

[method ready state]

           if (passivated)

               ejbActivate()

           execute method

           goto [method ready state]

 

[passivated]

            if (timeout) goto [does not exist]

 

[resources limited]

    ejbPassivate()

    goto [passivated]

 

[remove]   

    ejbRemove (may not be called, exception or crash)

 

Stateful Session Bean Lifecycle (from EJB 2.0 spec)

 

 

Page 184

 

1)      ejbRemove

2)      ejbPassivate

3)      ejbActivate

4)      setSessionContext

 

 

interface EJBContext

   EJBLocalObject getEJBLocalObject()

   EJBObject getEJBObject()

   Principal getCallerPrincipal()

   boolean getRollbackOnly()

   void setRollbackOnly()

  TimerService getTimerService()

  UserTransaction getUserTransaction()

  boolean isCallerInRole(java.lang.String role)

 

 

interface SessionContext extends EJBContext

   MessageContext getMessageContext() // JAX-RPC

 

 

Bean things

·        SessionContext

§         get reference to your home

§         get reference to your EJB Object

§         get security information about client

§         force a transaction to rollback (CMT)

§         find out if the transaction has already been set to rollback (CMT)

§         get a transaction reference and call methods on it (BMT)

·        Special JNDI Context (lookup following)

§         a reference to another bean

§         reference to a resource manager connection factory (like DataSource) that you can use to get for e.g a database connection

§         deploy-time constant values (like properties) for the bean (values set by deployer)

§         reference to an 'administered object' resource (usually JMS connection)

·        Access to

§         another bean

§         a resource manager (like a database)

 

What you can do on a bean varies by type (Session, Entity, Message-drive) and state e.g stateless beans cannot check client security information in ejbCreate(). Database information meaningful only in a transaction state

 

 

 

 

 

Container callback from two places: Session Bean interface and home interface, Session Bean must implement callbacks

Stateful session bean in 3 states: does not exist, method ready and passivated

 

 

 

 

Stateless Bean lifecycle

 

 

 

 

Bean things you can do in Stateless Bean methods (Page 228)

Note: no client information and no activation or passivation, we need on stateless bean per business method call

 

constructor: nothing

 

setSessionContext()

·        Use SessionContext to get a reference to your home

·        Access your special JNDI environment

 

business method

Use SessionContext to

·        get a reference to your home

·        get a reference to your EJB Object

·        get security information about the client

·        force a transaction to rollback (CMT beans)

·        find out if the transaction has already been set to rollback (CMT)

·        get a transaction reference and call methods on it (BMT)

·        access special JNDI environment

Access:

·        special JNDI Environment

·        another bean's methods

·        a resource manager (like a database)

 

ebjCreate() ejbRemove()

Use SessionContext to

·        get a reference to your home

·        get a reference to your EJB Object

Access:

·        special JNDI Environment

 

 

 

page 232

Rules for HOME methods: home interface

·        stateless bean LocalHome interface must extend EJBLocalHome and not throw RemoteException

·        stateless bean must have one one create() method and it must not have arguments

·        Remote home interface must extend EJBHome and declare RemoteException

·        stateful beans can have one or more create() methods, they must start with create e.g create() createSpecial()

·        Arguments and return types musts be RMI-IIOP types (Serializable, primitive, Remote, collections or arrays)

 

Rules for the Home methods: bean class

·        Every create method must have matching public void ejbCreate() (should not be final or static)

·        create method does not have to declare exceptions thrown by Home interface, good to thow CreateException (No RemoteException)

·        Cannot throw exceptions not listed in Home interface

·        stateless beans will have only one public void ejbCreate() {}

·        statefull bean match create from HOME interface ejbCreate() ejbCreateSpecial()

 

Rules for the BUSINESS methods: component interface

·        names must not begin with ejb

·        arguments and return types must be legal RMI-IIOP types

·        Local component interface must extend EJBLocalObject and must not declare RemoteExceptions -> public interface AdviceLocal extends EJBLocalObject {}

·        Remote component interfaces must extend EJBObject and must declare RemoteExceptions on every method

·        Don't expose the local home or component interface of a bean through a Remote component interface method

 

Rules for the BUSINESS methods: bean class

·        methods must be public, must not be final or static

·        method names must not begin with ejb

·        do not pass this as an argument or return value

·        Argument and return types must be legal RMI-IIOP types

·         

 

Entity Beans

·        An Entity Bean is a Java Object that represents a database entity (e.g row)

·        Entity Bean objects are cached and can be reused for different Database Entity Objects

·        Entity Bean remote component extends EJBObject

·        Entity Bean component interfaces have getter and setter methods e.g getName() setAge()

·        Same rule as remote component interface

·        Create() is optional in entity home

·        Entity Bean Home interfaces can have single-row or multi-row finder methods. Multi-finder return collection of component home interfaces. Create also return component home interface

·        Multiple-entity finders don’t throw exception for no entities found, they return empty list

·        Every entity bean should have atleast findByPrimaryKey()

·        Entity home interface can also have home business methods that apply to more than one entity e.g batch updates

·        Home business methods can return e.g collection of string

·        Entity bean create() will insert a new row into the database

·        Entity bean remove() deletes the entity from the database

·        Container makes sure that entity beans and database entity are in sync e.g. if database row deleted externally delete entity. Container has to make sure that Bean is not stale

·        Container will lock row if user calls a business method that changes data

·        Two types of persistence. CMP is the recommended way

o       BMP (Bean Managed Persistence)

o       CMP (Container Managed Persistence)

 

 

 

public interface EntityBean extends javax.ejb.EnterpriseBean (EnterpriseBeans implements Serializable {

     void setEntityContext(javax.ejb.EntityContext p1);

     void unsetEntityContext() ;

     void ejbRemove() ;

     void ejbActivate() ;

     void ejbPassivate() ;

     void ejbLoad() ;

     void ejbStore() ;

}

 

Entity

 

CMR (Container Manager relationship) for one to many relationship e.g. get Employees for a Department

Can define cascade delete in XML

Require local interface

 

Define entity relationship in ejb-jar.xml

 

  <relationships>

    <ejb-relation>

      <ejb-relation-name>EmpDept - Dept</ejb-relation-name>

      <ejb-relationship-role>

        <ejb-relationship-role-name>EmpDept may have one Dept</ejb-relationship-role-name>

        <multiplicity>Many</multiplicity>

        <relationship-role-source>

          <ejb-name>EmpDept</ejb-name>

        </relationship-role-source>

        <cmr-field>

          <cmr-field-name>dept_deptno</cmr-field-name>

        </cmr-field>

      </ejb-relationship-role>

      <ejb-relationship-role>

        <ejb-relationship-role-name>Dept may have many EmpDept</ejb-relationship-role-name>

        <multiplicity>One</multiplicity>

        <relationship-role-source>

          <ejb-name>Dept</ejb-name>

        </relationship-role-source>

        <cmr-field>

          <cmr-field-name>empDept_deptno</cmr-field-name>

          <cmr-field-type>java.util.Collection</cmr-field-type>

        </cmr-field>

      </ejb-relationship-role>

    </ejb-relation>

  </relationships>

 

Schema mapping in ejb-jar.xml file used by container to implement finder methods

    <entity>

      <description>Entity Bean ( CMP )</description>

      <display-name>EmpDept</display-name>

      <ejb-name>EmpDept</ejb-name>

      <local-home>ejbtut.empdept.EmpDeptLocalHome</local-home>

      <local>ejbtut.empdept.EmpDeptLocal</local>

      <ejb-class>ejbtut.empdept.EmpDeptBean</ejb-class>

      <persistence-type>Container</persistence-type>

      <prim-key-class>java.lang.Long</prim-key-class>

      <reentrant>false</reentrant>

      <cmp-version>2.x</cmp-version>

      <abstract-schema-name>EmpDept</abstract-schema-name>

      <cmp-field>

        <field-name>empno</field-name>

      </cmp-field>

      <cmp-field>

        <field-name>ename</field-name>

      </cmp-field>

      <cmp-field>

        <field-name>job</field-name>

      </cmp-field>

      <cmp-field>

        <field-name>mgr</field-name>

      </cmp-field>

      <cmp-field>

        <field-name>hiredate</field-name>

      </cmp-field>

      <cmp-field>

        <field-name>sal</field-name>

      </cmp-field>

      <cmp-field>

        <field-name>comm</field-name>

      </cmp-field>

      <primkey-field>empno</primkey-field>

      <query>

        <query-method>

          <method-name>findAll</method-name>

          <method-params/>

        </query-method>

        <ejb-ql>select object(o) from EmpDept o</ejb-ql>

      </query>

    </entity>

 

EJB-QL (EJB-Query Language)

It is a SQL based language

 

Select object(o) from emp o where o.job = ‘Analyst’

Select object(o) from emp o where o.job = ?1

 

 

Message driven bean

 

 

Transactions

Transactions should pass ACID test

·        Atomic:  Works or fails, no in between state

·        Consistent: Data should stay consistent

·        Isolated: Transactions are protected from each other

·        Durable: Changes are permanent on commit, even if server goes down

 

Distribute Transactions (update two databases)

·        Phase One: Are you ready

·        Phase Two: Commit All

 

Two ways to make a transaction

·        BMT (Bean Managed Transactions)

·        CMT (Container Managed Transaction

 

Transactions can propagate through method calls, BMT transactions can propagate out to a CMT

CMT transactions do not propagate to BMT, they are suspended (means if outer transaction fails after inner commit, only outer rolled back)

When a bean is running code in a transaction and calls a method on another bean three different scenarios are possible

·        The called method runs in the callers’ transaction

·        The called method runs without a transaction

·        The called method runs within its own new transactaion

 

 

BMT

Cannot nest transactions i.e. two nested UserTransaction.begin()

Stateless or message drive beans have to complete transaction within method

BMT makes method hard to reuse

In DD <transaction-type>Bean</transactiontype>

UserTransaction ut = context.getUserTransaction();

ut.begin();

ut.commit(); // or ut.rollback();

 

CMT

In DD <transaction-type>Container</transactiontype>

 

<method>

  <ejb-name>MyBean</ejb-bean>

  <method-name>foobar</method-name>

</method>

<trans-attribute>Required</trans-attribute>

 

 

javax.transaction.UserTransaction // BMT only

     begin(), commit(),

getStatus(), // BMT way to check if transaction marked for rollback

rollback(),

setRollbackOnly(),

setTransactionTimeout()

 

javax.ejb.EJBContext // BMT and CMT

     getUserTransaction() // BMT only

     // BMT and CMT

     getCallerPrincipal()

getEJBHome()

getEJBLocalHome()

isCallerInRole()

// CMT only

setRollbackOnly() // CMT way for code to mark rollback,

getRollbackOnly() // CMT way for code to check if rollback will happen, call in transaction only

 

 

SessionContext, EntityContext, MessageDrivenContext extend EJBContext

 

 

CMT Transaction Attributes

·        Required  // use existing transaction else create new

·        Requires New // always run with new transaction, callers transaction is suspended

·        Mandatory // throw exception if not caller not in transaction

·        Supports // run in callers transaction else in unspecified transaction context (use Supports for read only to avoid deadlocks?)

·        NotSupported // caller transaction suspended and runs in unspecified transaction context

·        Never // throw exception if called with transaction context

 

Methods to mark with attributes

·        Session Bean business method in the component interface with Transaction Attributes

·        Business method in the component interface

·        MDB onMessage() method, will use only Required and NotSupported attribute

 

Transactions

·        Note system exceptions cause automatic rollback

·        After rollback Container loads data from database and calls ejbLoad() so that EntityBean is in sync with database

·        Stateful Session Beans can implement SessionSynchronization to know transaction events

·        Stateless beans don’t have transaction once method ends

 

SessionSynchronization // for Stateful Session CMT Beans

afterBegin() // similar to ejbLoad, can cache data over here

beforeCompletion() // similar to ejbStore called before transaction ends and after method completes

afterCompletion(boolean commited) // after transaction has commited or rollback

 

 

 

Marking transactions in DD, specified in assembly part and not bean part

<enterprise-beans>

  <session> … <transaction-type>Container</transaction-type> </session>

</enterprise-beans>

 

<assembly-descriptor>

  <container-transaction>

    <method>

      <ejb-name>MyBean</ejb-name>

      <method-name>foo</method-name> <!-- can use wild card -->

          <!-- optional method-param for overloaded method à

    </method>

    <method>

      <ejb-name>MyBean</ejb-name>

      <method-name>bar</method-name> <!-- can use wild card -->

    </method>

    <trans-attribute>Required</trans-attribute>

  </container-transaction

</assembly-descriptor>

 

 

Exception Management

Bean Exception

·        Validation Exception e.g. credit card invalid for purchase

·        Checked exception e.g JNDI lookup

·        Runtime exception (NullPointerException

Container Exception

·        Container can’t complete an operation, causes a problem that client expects

·        Container catches a checked exception thrown by the bean, that the client expects

·        Container catches runtime exception that the client does not expect

RMI System exception

·        EJB throws runtime exception before it communicates with client

·        RMI subsystem cannot communicate with client

·        Client stub throws a runtime exception

 

Application Exception

·        e.g ObjectNotFound, CreditCardInvalidException etc

·        Must be checked excetion

·        Transaction not rolled back

·        Client can recover

System Exception, exceptions that application cannot recover from

·        Transaction rolled back

·        Bean is destroyed and exception is logged

·        Exceptions are unchecked

·        RemoteException is checked exception

 

Remote entity bean home interface has Application and System Exception (RemoteException)

Local  entity bean home interface has only Application Exception,

Local clients get EJBException (unchecked) and remote client gets RemoteException

 

Bean providers responsibility

·        If business logic throws or creates application exception throw it to container

·        If you catch application exception and want to rollback, do the rollback and then throw exception to container

·        Throw EJBException to client for unrecoverable errors

·        Don’t catch runtime exceptions let container handle it

·        Bad idea to do try { .. } catch (Exception e) {}

·        Declare application exception in both client and interface and bean class

·        Application Exception should extend Exception and not RuntimeException

Standard EJB Exceptions

·        CreateException (client cannot know if bean was created)

·        DuplicateKeyException extends CreateException (client knows bean not created)

·        FinderException -> thrown from finder method for CMP Beans only container can throw this (client does not know whether a matching entity exists in the database)

·        ObjectNotFoundException extends FinderException -> container throws to client for single-entity finder method (client can be sure object does not exist)

·        RemoveException -> (client cannot be sure bean was removed) if remove not supported for an entity throw exception e.g list of countries

 

Common system exceptions for local clients

·        javax.ejb.EJBException e.g when setRollbackOnly() is called and not in transaction

o       javax.ejb.NoSuchObjectLocalException -> called on bena which was removed

o       javax.ejb.NoSuchEntityException ->

o       javax.ejb.TransactionRequiredLocalException -> thrown for methods marked mandatory and no exception

o       javax.ejb.TransactionRolledbackLocalException ->

·        java.lang.IllegalAccessException

Common system exceptions for remote clients

·        java.rmi.NoSuchObjetException

·        javax.transaction.TransactionRequiredException

·        javax.transaction.TransactionRolledbackException

 

Security

Declarative Security

·        Can set what role can access which method

·        Define roles in <security-role> for each role

·        <role-name> is the role name

·        Creating user and assigning user to role is container specific

 

<assembly-descriptor>

  <security-role>

     <description> Admin role </description> <!-- optional -->

    <role-name>Payroll Admin</role-name>

  </security-role>

 

  <method-permission>

    <role-name>Payroll Admin</role-name>

    <ejb-name>ChangePay</ejb-name>

    <method-name>setSalary</method-name> <!-- can use wildcard -->

          <-- optional args for overloaded methods -->

  </method-permission>

 

  <method-permission>

    <unchecked/> <!-- anybody can call -->

    <ejb-name>PersonDetails</ejb-name>

    <method-name>getPhone</method-name> <!-- can use wildcard -->

          <-- optional args for overloaded methods -->

  </method-permission>

 

</assembly-descriptor>

 

Programmatic Security

java.security.Principal p = context.getCallerPrincipal();

String name = p.getName();

if (context.isCallerInRole(“Payroll Admin”)) {}

 

// map programmatic names to declarative names using <security-role-ref>

 

 

Use <run-as> to change role for a method

 

 

 

 

 

*********************************************************************************************************

 

Creating EJB in JDeveloper

 

 

JDeveloper create EJB Application

·        Create Database connection

·        Create Entity Bean

·        Create Session Bean

·        Right click on SessionBean to generate New Sample Java Client

·        Click Run on Session Bean to start OC4J

·        Run Sample Java Client

 

Sun Certified Business Component Developer

SunCertified Website has notes

 

Hibernate

 

Not good for stored procedures

 

Problem with EJB

Produces procedural code

 

Introduction to Hibernate

Hibernate your Data

 

 

 

 

 

 

 

 

 

// Somebody elses notes

 

 

 

 

 

 

 

1. Method getEJBMetaData() is defined in which interface? EJBHome

 

2. Stateless Session Bean

? When client invokes create(), its not deligated to bean instance’s ejbCreate()

? Never passivated / activated so ejbActivate() / ejbPassivate() never invoked

? When client invokes one of remove() methods, its not delegated to bean instance’s ejbRemove() method. ejbRemove() is invoked by the container whenever it don’t need the bean instance anymore

? Session context and JNDI ENC are available to the bean when executing ejbRemove()

? Which of the methods can be invoked on a stateless session bean when its in method ready state

? Business methods

? ejbRemove()

? From business methods only we can access resource manager and other beans but not from ejbRemove() or ejbCreate()

? Remember, from ejbCreate() u cant access another bean

? From setSessionContext, you can’t access your EJBObject – it’s executed before any client makes any call.

? Must not implement SessionSynchronization.

 

3. Exceptions

? MDB can throw system exceptions upon which, the container discard the bean instance, however those exceptions are not propagated to the client as there is no client – due to the same reason, MDBs cant throw application exception.

? When system exception occurs in a session bean, the bean instance is discarded, thus client’s conversational state is lost and the bean instance’s reference held by the client is invalidated.

? If an entity bean instance method is executing in a client’s transactional context and throws a system exception, the exception is throws again as TransactionRolledbackException to remote client and TransactionRolledbackLocalException to local client.

? (javax.ejb.) CreateException, RemoveException and FinderException are application exception

? javax.transaction.TransactionRolledbackException is subclass of java.rmi.Remote and javax.transaction.TransactionRolledbackLocalException is subclass of javax.ejb.EJBException – both are system exception

? NoSuchEntityException is subclass of EJBException – so system exception – thrown to indicate that underlying entity has been removed from the database

? Javax.ejb.ObjectNotFoundException is subclass of javax.ejb.FinderException, which is an application exception throws by single entity finder methods – if no mathcing primayr key is found.

 

4. Guaranteed capabilities of EJB 2.0

? To provide local client view and support for efficient, lightweight access to enterprise beans from local clients

? To provide network-interoperability between EJB servers

? Read only CMP entity beans may or may not be supported

 

5. MDB

? Attached to a message destination, not any client

? Supports bean managed transaction (BMT) demarcation but not bean managed persistence (BMP)

? They are stateless component, so don’t maintain conversational state

? MessageDrivenBean interface defines two methods – ejbRemove() and setMessageDrivenContext()

? For MDB if <security-identity> is specified, <use-caller-identity> can’t be used as it has no client-view. Only <run-as> can be specified. <run-as> is used when bean is to act as someone other than the calling client. This new identity (<run-as> would be used when call to other EJB would be made.

 

6. Stateful session bean

? Transient variables are not passivated

? Home and component interface types are passivated

? If bean timeouts during passivated state, its ejbRemove() is not invoked

? Access to resource manager and other beans are not allowed from bean constructor, setSessionContext, and afterCompletion. From other methods – ejbCreate, business methods and beforeCompletion its allowed.

? A stateful session bean calculates compound interest based on the interest rate, which can be read by the bean at run-time. This is achieved with env-entry element in the deployment descriptor.

? When client invokes create() method on bean’s home interface, Class.newInstance() is invoked, sessionContext is set and appropriate ejbCreate<METHOD>() is called. Now bean is in method-ready state.

? The container passivate the bean, and after time-out remove bean instance by calling ejbRemove().

? What do local and remote component interfaces of session bean have in common?

? Removing the session bean & Retrieving their respective home interface

? Creating a new session bean is responsibility of remote/local home

 

7. Entity bean

? Which method of local home interface takes primary key type as an argument and return type is entity’s local interface – findByPrimaryKey – this method cant be overloaded

? An entity bean always uses CMT – so a bean itself can’t manage its own transaction. Its not even allowed to retrieve UserTransaction object from JNDI ENC and invoke methods on it. If it tries to, the container would throw java.naming.NameNotFoundException.

? Interface javax.ejb.HomeHandle must be implemented by an entity bean’s home handle class.

? Only ejbActivate(), ejbPassivate(), setSessionContext(), unsetSesionContext() runs in ‘unspecified transaction context’ otherwise all others need transactional context or u get java.lang.IllegalStateException.

? An entity bean can be passivated only when it’s in (method) ready state. It can be passivated just after being activated as after activation it comes to ready state.

 

8. DD - EJB Reference (<ejb-ref>

? Its responsibility of bean provider to declare all ejb references in DD

? EJB Reference is scoped to the enterprise bean whose declaration contains <ejb-ref> or <ejb-local-ref> element. This means EJB Reference is not available to other enterprise beans at run-time and other enterprise beans may define <ejb-ref> or <ejb-local-ref> element with the same name without causing a name conflict.

? <ejb-ref> element contains description, <ejb-ref-name>, <ejb-ref-type>, <home> and <remote> elements

? <ejb-ref> element is used for referencing an enterprise bean that is accessed through its remote home and remote interface. It’s required child elements are <ejb-ref-name> (specified ejb reference name, its name is used in bean code), <ejb-ref-type> (specifies bean type – session or entity), <remote> and <home> (referenced bean’s remote and home interface). <ejb-link> (optional, used by assembler to link to target bean, must be equal to corresponding bean’s <ejb-name> and <description> are optional fields.

 

9. Entity bean – primary key

? Primary key fields cant be modified by the client once it is set

? Primary key fields must follow RMI-IIOP as being used in remote invocation

? In some cases bean provider may choose not to specify primary key class or field, in that case primary key class / field would be specified at deploy time

? The primary bean class must be public, implement java.io.Serializable and have public no-arg constructor. All fields in primary key class must be public.

? The name of fields in primary key class must be subset of CMP fields.

? There must not be any mutator (set<FIELD_NAME> in component interface for any of primary key fields.

 

10. Security

? If the <use-caller-identity> is specified as child of <security-identity> element, the called enterprise bean will always see the same returned value of EJBContext.getCallerPrincipal() as the calling enterprise bean.

? DD : Security role reference <security-role-ref>

Defined by bean provider. Scoped within session or entity bean whose declaration contains <security-role-ref>

<security-role-ref>

<role-name>Administrator</role-name> //hard coded by bean provider

<role-link>Root</role-link> //defined in <security-role> by assembler

</security-role-ref>

 

11. EJBs Requirements

? EJBs are not allowed to create or install a new security manager, as this would create a security risk.

? EJBs are allowed to invoke Class.getResource in order to retrieve bundled resources (text, images, properties etc), bundled within the same enterprise application archive.

? EJBs are not allowed to return or pass ‘this’ as an argument to another bean’s method, but they are allowed to use ‘this’ reference to access its their own members.

? EJBs are not supposed to use synchronized block or declare their methods to be synchronized

 

12. EJB Recommendation

? Organize all references to enterprise beans in ejb sub-contexts

? Organize all references to JDBC datasource in jdbc sub-context

? Organize all resource environment reference to in jms sub-context

 

13. DD - <res-auth>

? Used when sign-on procedure for a resource manager must be specified

? Two possible values

? Application – means enterprise bean sign-on programmatically to the resource manager

? Container – means the container would perform sign-on on behalf of the application using information provided by the deployer

 

14. EJBContext

? Methods defined in this interface

? getCallerPrincipal, isCallerInRole (client)

? getRollbackOnly, setRollbackOnly (CMT)

? getUserTransaction

? getEJBHome, getEJBLocalHome

? public void java.security.Principal getCallerPrincipal()

? Session context defines additional methods: getEJBObject(), getEJBLocalObject

? Entity context defines additional methods: getEJBObject(), getEJBLocalObject(), getPrimaryKey()

? MessageDrivenContext don’t defines any additional methods

 

15. EJB-QL

? EJB-QL defines &, ==, != as AND, =, <>

 

16. Transaction

? What if a bean with CMT tries to retrieve a UserTransaction object through JNDI by looking up the java:comp/UserTransaction name?

The container would throw javax.naming.NameNotFoundException

? What is counterpart of javax.transaction.TransactionrequiredException for local clients?

Javax.ejb.TransactionRequiredLocalException – these two exceptions are throws to remote / local clients whenever a system exception is thrown from a method that runs in caller’s transaction context (possible with mandatory, supporrts and required attributes)

? <transaction-type> element is used to specify which transaction type – CMT or BMT being used. As entity bean can only use CMT, this element can only be specified for Session and Message beans. This is responsibility of bean provider.

? When a business methos that executes in the transactional context of caller and throws javax.ejb.EJBException – the container is required to throw javax.ejb.TransactionRollbackLocalException to the client (local)

? If the business method’s transactional attribute were mandatory and the client (local) were trying to access it without a transactional context, it would receive javax.transaction.TransactionRequiredLocalException

? A bean which want to use SessionSynchronization (except of course, stateless bean) must not use transactional attributes of Never, NotSupported or Supports. Bean has to be in transactional state before it can ask for its transactional status.

? For portability, an entity bean must use Required, RequiresNew or Mandatory.

? To use EJBContext’s setRollbackOnly()/getRollbackOnly() the TA must be Required, RequiresNew, Mandatory.

? The assembler uses <container-transaction> to define transactional attributes

< container-transaction>

<method>

<ejb-name>MyEJB</ejb-name>

<method-name>*</method-name>

</method>

<trans-attribute>Required</trans-attribute>

</ container-transaction>

? If methods are overloaded <method-params> and <method-param> could be used.

? BMT – provider uses javax.transaction.UserTransaction to explicitly demarcate transactions. Pseudo code:

UserTransaction ut = ejbContext.getUserTransaction();

ut.begin();

method1();

method2();

...

if(someSuccessCondition)

ut.commit();

else

ut.rollback();

 

17. Environment Context

? Following string used for JNDI lookup of managed server resources (JMS resources) – java:comp/env/jms/StockQueue

 

18. Apart from <ejb-name> in <relationship-role-source> which other element should an assembler never modify - <abstract- schema-name>

 

19. Write class name that is used to perform type-narrowing of client side representation of remote interface. – javax.rmi.ProtableRemoteObject

 

20. Which DD element is used to specify entity bean type in EJB-QL?

<abstract-schema-name>

 

21. Child elements of <ejb-jar>

? <display-name>

? <ejb-client-jar>

? <enterprise-beans>

? <assembly-descriptor>

? <small-icon>

 

22. BMT (session and message driven) are responsible for managing their own transactions – they can start new transaction (using context.getUserTransaction()) in any method except for setSessionContext()/SetMessageDrivenContext()

 

23. CMT Session and Message Driven beans’ create method runs in “unspecified transaction context”

 

24. Which DD element bean provider can use to tell deployer which destination a message driven bean should be associated with - <destination-type> (value – javax.jms.Queue / javax.jms.Topic)

 

25. Only for stateless session bean (both BMT & CMT) there exists the restriction that a transaction must not span multiple method calls – which means for others (stateful – both BMT & CMT - and enitty ) a transaction can span multiple method calls. [bit doubtful – in CMT transaction scope is method-level – so a transaction will only span for a single method call – verify this)