Pages

Subscribe Twitter Twitter

Monday, August 2, 2010

EJB FAQS

EJB Questions


Q) Application server & Web server
 Application server is a generalized server for running more than one application like ejb, rmi, jsp, servlets.
 webserver is for request, response paradigm. It takes the client request and send response back to the client and the connection is closed.
 A.S cannot process Http request, but takes the forwarded request from W.S and process the business logic and send the output to the W.S which it turns send to the client.
 A.S manage transactions, security, persistence and lot more, but W.S cannot help in this regards. W.S takes only the Http request.
 A.S provides runtime environment for server side components, they provide middleware services such as resource pooling and network.

Q) Diff Bean & Ejb

Q) SessionBeans
Session beans are not persistence there are short lived beans. S.B can perform database operations but S.B it self is not a persistence objects. S.B are business process objects they implements business logic, business rules and workflow.

Statefull Session Bean & Stateless Session Bean

 Statefull session bean is a bean that is designed to service business process that span multiple methods request/transaction, S.S.B can retain their state on the behalf of individual client. All S.S.B can exposes only a single ejbCreate() method it does not take any parameters.
 Stateless session bean these are single request business process is one that does not require state to be maintained across method invocation. S.S.B cannot hold the state.
 Statefull session bean do not have pooling concept
 Stateless session bean instance can be pooled.
 If the business process span multiple invocations there by requiring a conversational then S.S.B will be ideal choice.
 If the business last only for a single method call, S.S.B are suitable.

Q) Entity Bean
Entity beans are permanent business entities because their state is saved in permanent data storage. E.B are persistence objects, E.B contain data related logic. E.B are permanent so if any machine crashes, the E.B can be reconstructed in memory again by simple reading the data back in from the database.

Bean managed Persistence & Container managed Persistence
 B.P is an entity bean that must be persisted by hand, other words component developer must write the code to translate your in-memory fields into an underlying data store. You handle these persist operations your self, you place your data base calls in ejbLoad() and ejbStore(). Finder methods only for B.M.P for C.M.P your ejb container will implement the finder methods. In this commit, rollback, begin are transactions In B.M.P findByPK() return a reference to the actual bean object.
 You do not have to do anything to synchronize with data base. In entity bean deployment descriptor you specify which fields that the container should manage. The transaction in C.M.P are TX-Support, TX-NotSupport, TX-require. He findByPK() in C.M.P return void because the method is internally implemented.

Q) Message Driven Bean
 M.D.B process messages asynchronously are deliver via JMS. M.D.B’s are stateless, server side, transaction aware components used for asynchronous JMS messages. It acts as a JMS message listener which JMS messages, the messages may be sent by any J2ee component, an application client, another enterprise bean, or by a JMS application.
When Ejb application server starts it parse the D.D and then loads and initializes declared beans. In case of M.D.B container establish a connection with the message provide(MOM server), client access message beans through the beans JMS interface (java.JMS.messageListerner) which exposes a single method.
Public void onmessage(javax.JMS.message message)




Q) When to use container managed and bean managed persistence?
Container managed persistance is used when the persistant data store is a relational database and there is one to one mapping between a data represented in a table in the relational database and the ejb object.
Bean managed persistance in used when there is no one to one mapping of the table and a complex query reteriving data from several tables needs to be performed to construct an ejb object. Bean managed is also used when the persistence data storage is not a relational database.

Q) When to choose Statefull & Stateless Session bean?
A) Does the business process span multiple method invocations, requiring a conversational state if so the state full model fits very nicely. If your business process last for a single method call the stateless paradigm will better suite needed.

Q) Diff Statefull Session & Entity Bean
Both S.S.B & E.B undergo passivation and activation. The E.B have a separate ejbStore() callback for saving state during passivation & a separate ejbLoad() callback for loading state during activation. We do not need these callbacks for S.S.B because the container is simply uses object serialization to persist S.S.B fields.

Q) Object-Relational Mapping
Mapping of objects to relational database is a technology called O.R.M. O.R.M is a persistence mechanism of persistence objects than simple object serialization.

Q) When to use which bean Session Bean & Entity Bean?
 E.B are effective when application want to access one row at a time, if many rows needed to be fetched using session bean can be better alternative.
 E.B are effective when working with one row at a time cause of lot of N.W traffic. S.B are efficient when client wants to access database directly, fetching, updating multiple rows from data base.
 S.B for application logic.

Q) Deployment Descriptor
D.D contains information for all the beans in the “ejb.jar” file. D.D enables ejb container to provide implicit services to enterprise bean components, these services can gain your bean with out coding. D.D is a XML file.

Q) ejbCreate()
In stateless session bean can have only one ejbCreate() method it must take no arguments. Remember that ejbCreate() is essentially analogous to a constructor for ejb; it initializes an instance internal state variable. Because the stateless session bean has no client specific variables.

Q) Can a Session Bean be defined without ejbCreate() method?
A) The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method.

- The home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments.
- Stateful Session Beans can have arguments (more than one create method)
- Stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition

Q) Can i call remove() on a Stateless Session bean?
A) Yes, The life of a Stateless Session bean for a client is just till the execution of the method that the client would have called on the bean…after the execution of that method if the client calls another method, then a different bean is taken from the pool. so the container very well knows that a bean has finished its life for a client and can put it back in the pool.

Q) Can a Stateless Session Bean maintain state?
A) Yes, A Stateless Session bean can contain no-client specific state across client invoked methods. For ex states such as socket connection, dbase connection, references to an EJBObject and so on can be maintained.

Q) How can I map a single Entity Bean to multiple tables?
A) If u use Bean-Managed Persistence(BMP), map the bean to tables manually. Consider applying the DAO design pattern to accomplish this,.
If u choose Container-Managed persistence(CMP), use the vendors object/relational mapping tool to specify the mapping between your object state and the persistence schema.

Q) Can EJB handle transaction across multiple databases?
A) The transaction manager in EJB handling transaction across multiple databases. This is accomplished with multiple Entity beans handling to each database and a single session bean to manage a transaction with the Entity bean.

Q) Session Bean CallBack methods?
public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean
{
public abstract void ejbActivate();
public abstract void ejbCreate();
public abstract void ejbPassivate();
public abstract void ejbRemove();
public abstract void setSessionContext(SessionyContext ctx);
}

SessionContext  S.C is your beans gateway to interact with the container, S.C query the container about your current transactional state, your security state.

ejbCreate()

ejbPassivate( )  If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here, ie,close socket connections..etc.

ejbActivate( )  When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection

ejbRemove() container wants to remove your bean instance it will call this method.

Q) Entity Bean CallBack methods?
public interface javax.ejb.EntityBean extends javax.ejb.EnterpriseBean
{
public abstract void ejbActivate();
public abstract void ejbLoad();
public abstract void ejbPassivate();
public abstract void ejbRemove();
public abstract void ejbStore();
public abstract void setEntityContext(EntityContext ctx);
public abstract void unsetEntityContext();
}

Q) EJBContext Rollback Methods

EJBContext interface provides the methods setRollbackOnly() & getRollbackOnly().
setRollbackOnly( )Once a bean invokes the setRollbackOnly() method, the current transaction is marked for rollback and cannot be committed by any other participant in the transaction--including the container.
getRollbackOnly( )  method returns true if the current transaction has been marked for rollback. This can be used to avoid executing work that wouldn't be committed anyway.

Q) How can I call one EJB from inside of another EJB?
A) EJB can be clients of another EJB’s. it just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance.




Q) Conversational & Non-conversational
Conversational is an interaction between the bean and client, stateless session bean is a bean that do not hold multi method conversation with clients. Stateless.S.B cannot hold state, Statefull.S.B can hold conversational with client that may span multiple method request.

Q) JNDI to locate Home Objects
H.O are physically located some where on the N.W, perhaps in the address space of the Ejb Container. For client to locate H.O, you must provide nick name for your beans H.O. Client will use this nick name to identify the H.O it wants, we will specify the nice name in the Deployment descriptor. Container will use this nick name, JNDI goes over the N.W to some directory service to look for the H.O.

Properties props = System.getProperties();
Context ctx = new InitialContext(props);
MyHome home = (MyHome)ctx.lookup(“MyHome”);
MyRemoteInterface remote = home.create();

Q) Diff servlet/jsp session & EJB session
 logical point of view a servlet/jsp session is similar to an ejb session. A session in servlet is maintained by the servlet container through Http session object.. That is acquiring through the request object. You cannot instantiate Http session object.
 A session in Ejb is maintained using S.B, you design bean that can maintain business logic. You can have 2 types of beans 1. Stateless 2. Stateful.

Q) ejbCretae( ) & ejbPostCreate( )
 ejbCreate() is called just before the state of the bean is written to the persistence storage. After this method is completed a new record is created and written.
 ejbPostCreate() is called after the bean has been written to the database and the bean data has been assigned to an Ejb object.

Q) Can map Entity bean to more than one table?
A)

Q) EAR, WAR, JAR
 All EJB classes should package in a JAR file, All web components pages, servlets, gif, html, applets, beans, ejb modules, classes should be packaged into WAR file. EAR file contain all the JAR & WAR files. Note that each JAR, WAR, EAR file will contain D.D

Q) Life cycle

Life cycle of a Stateful Session Bean

- Stateful session bean has 3 states Does Not Exist, Method Ready Pool and Passivated states.
- A bean has not yet instantiated when it is in the Does Not Exist Sate.
- Once a container creates one are more instance of a Stateful Session bean it sets them in a Method Ready State. In this state it can serve requests from its clients. Like Stateless beans, a new instance is created(Class.newInstance()), the context is passed (setSessionContext()) and finally the bean is created with the ejbCreate().
- ejbPassivate( ) If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here,ie,close socket connections..etc.
- ejbActivate( ) When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection




Life cycle of a Stateless Session Bean : -

- A S.S.B has only two states: Does Not Exist and Method Ready Pool.
- A bean has not yet instantiated when it is in the Does Not Exist Sate.
- When the EJB container needs one are more beans, it creates and set then in the Method Ready Pool Sate. This happens through the creation of a new instance(Class.newInstance()), then it is set its context (setSessionContext()) and finally calls the ejbCreate() method.
- The ejbRemove() method is called to move a bean from the Method Ready Pool back to Does Not Exist State.



Life cycle of Entity bean
- Bean instance “Dose not exist” state represent entity bean instance that has not been instantiated yet.
- To create a new instance container calls the newInstance() on entity bean class.
- After step 2 E.B is in a pool of other E.Bs. At this point your E>b does not have any E.B data base data loaded into it and it does not hold any bean specific resources (socket & database connections) .If the container wants to reduce it’s pool size it can destroy your bean by calling unsetEntityContext() on your bean.
- When the client wants to create some new data base data it calls a create() method on entity beans HomeObject. The container grabs the beans instance from the pool and the instance ejbCreate() method is called.
- E.B to be kicked back to pool, if a client call ejbremove() method.
- ejbPassivate( ) If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here, ie,close socket connections..etc.
- ejbActivate( ) When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection
-



Life cycle of M.D.B


Does Not Exist
When an MDB instance is in the Does Not Exist state, it is not an instance in the memory of the system. In other words, it has not been instantiated yet.

The Method-Ready Pool
MDB instances enter the Method-Ready Pool as the container needs them. When the EJB server is first started, it may create a number of MDB instances and enter them into the Method-Ready Pool. (The actual behavior of the server depends on the implementation.) When the number of MDB instances handling incoming messages is insufficient, more can be created and added to the pool.

Transitioning to the Method-Ready Pool
When an instance transitions from the Does Not Exist state to the Method-Ready Pool, three operations are performed on it. First, the bean instance is instantiated when the container invokes the Class.newInstance() method on the MDB class. Second, the setMessageDrivenContext() method is invoked by the container providing the MDB instance with a reference to its EJBContext. The MessageDrivenContext reference may be stored in an instance field of the MDB.
Finally, the no-argument ejbCreate() method is invoked by the container on the bean instance. The MDB has only one ejbCreate() method, which takes no arguments. The ejbCreate() method is invoked only once in the life cycle of the MDB.

Q) EJB Resources?

text
name
Java type
mycom.ejb.AccountHome
mycom.ejb.Account
ejb.name
security role


Q How to deploy in J2EE (i.e Jar, War file) ?

Each web application should be contained in a war (web archive) file. War files are nothing but a jar file containing atleast one descriptor called web.xml. The file structure of war file is:

/--
|
| WEB-INF
| |
| |-- WEB.XML (Deployment descriptor)
| |-- classes (Folder containing servlets and JSPs
|
| META-INF
| |
| |-- MANIFEST.MF
|
| all utility files and resources like error pages etc.

Each enterprise bean is stored in a jar file. The jar file contains all standard files like manifest and atleast one additional file called ejb-jar.xml. The structure of a jar file is:

/--
|
| META-INF
| |
| |-- MANIFEST.MF
| |-- ejb-jar.xml
|
| all classes as in a normal jar file.

Both jar and war files are placed inside a ear (enterprise archive) file. The structure of an ear file is

/--
|
| META-INF
| |
| |-- MANIFEST.MF
| |-- application.xml
|
| jar and war files.



Q) Deployment descriptor of EJB


JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">



This Deployment includes all the beans needed to make a reservation:
TravelAgent, ProcessPayment, Reservation, Customer, Cruise, and Cabin.



TravelAgentBean
com.titan.travelagent.TravelAgent
...


CustomerBean
com.titan.customer.Customer
...


ProcessPaymentBean
com.titan.processpayment.ProcessPayment
...

...


...

...


Q)
Remote Interface

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

Home Interface

public interface HelloHome extends javax.ejb.EJBHome
{
Hello create() throws java.rmi.RemoteException; javax.ejb.CreateException;
}

Bean Class

public class HelloBean implements javax.ejb.SessionBean
{
private SessionContex ctx;
public void ejbCreate();
public abstract void ejbRemove();
public abstract void ejbActivate();
public abstract void ejbPassivate();
public abstract void setSessionContext(SessionyContext ctx);

public String hello(){
System.out.println(“hello());
Return “hello world”;
}

Client

public class HelloClient
{
public static void main(String args[ ])
properties props = system.getProperties();
Context ctx = new InitialContext(props);
Object obj = ctx.lookup(“HelloHome”);
HelloHome home = (HelloHome)
javax.rmi.protableRemoteObject.narrow(obj, HelloHome.class);
Hello hello = home.create();
System.out.println(hello.hello());
Hello.remove();
}

Q) Transaction Isolation levels

TRANSACTION_READ_UNCOMMITTED
The transaction can read uncommitted data. Dirty reads, nonrepeatable reads, and phantom reads can occur. Bean methods with this isolation level can read uncommitted change.

TRANSACTION_READ_COMMITTED
The transaction cannot read uncommitted data; data that is being changed by a different transaction cannot be read. Dirty-reads are prevented; nonrepeatable reads and phantom reads can occur. Bean methods with this isolation level cannot read uncommitted data.

TRANSACTION_REPEATABLE_READ
The transaction cannot change data that is being read by a different transaction.
Dirty reads and nonrepeatable reads are prevented; phantom reads can occur. Bean methods with this isolation level have the same restrictions as Read Committed and can only execute repeatable reads.

TRANSACTION_SERIALIZABLE
The transaction has exclusive read and update privileges to data; different transactions can neither read nor write the same data. Dirty reads, nonrepeatable reads, and phantom reads are prevented. This isolation level is the most restrictive.

Dirty-read  When your application reads data from a database that has not been committed to permanent storage yet.

Un-repeatable read  When a component reads some data from a database, but upon reading the data, the data has been changed. This can arise when another concurrently executing transaction modifies the data being read.

Phantom-read  A phantom is a new set of data that magically appears in a database between two database read operations.

Q) Diff Phantom & Un-repeatable
Un-repeatable occurs when existing data is changed, where as phantom read occurs when new data is inserted that does not exist before.

Q) Transaction Attributes

TX_BEAN_MANAGED  Then your bean programmatically controls its own transaction boundaries. When you using programmatically transaction, you issue the begin, commit & abort statements.

TX_NOT_SUPPORTED  If you set this your bean cannot be involved in a transaction at all.

TX_REQUIRED  If you want your bean to always run in a transaction. If there is a transaction already running your bean joins in on that transaction. If there is no transaction running, the container starts one for you.

TX_REQUIRES_NEW  If you always want a new transaction to begin when your bean is called we should use this. If there is a transaction already underway when your bean called, that transaction is suspended during the bean invocation. The container then launches a new transaction and delegate the call to the bean.

TX_SUPPORTS  When a client call this it runs only in a transaction if the client had one running already; it then joins that transaction. If no transaction =, the bean runs with no transaction at all.

TX_MANDATORY  Is a safe transaction attribute to use. It guarantees that your bean should run in a transaction. There is no way your bean can be called if there is not a transaction already running.

Q) ACID Properties
When you properly use transaction your operations will execute ACID properties.

(i) Atomicity  Guarantees that many operations are bundled together and appears as one contiguous unit of work.
Ex:- When you transfer money from one bank account to another you want to add funds to one account and remove funds from the other transaction and you want both operations to occur or neither to occur.

(ii) Consistency  Guarantees that a transaction will leave the system state to be consistent after a transaction completes.
Ex:- A bank system state could be consist if the rule “bank account balance must always be +ve”.

(iii) Isolation  Protect concurrently executing transaction from seeing each other incomplete results.
Ex:- If you write a bank account data to a database, the transaction may obtain locks on the bank account record (or) table. The lock guarantee that no other updates can interfere.

(iv) Durability  Resources keep a transactional log for resources crashes, the permanent data can be reconstructed by reapplying the steps in the log.

Q) Diff Sax & DOM

DOM SAX
1. Tree of nodes
2. Occupies more memory preferred for small XML documents
3. Slower at runtime
4. Stored as objects
5. Programmatically easy, since objects
6. Easy of navigation
7. DOM creates a tree structure in memory 1.Sequence of events
2.Does not use any memory preferred for large documents.
3.Faster at runtime
4.Objects are to be created
5.Need to write code for creating objects are to referred
6.backward navigation is not possible

Q) Hot deployment
Hot Deployment in Web Logic is he act of deploying, re-deploying and un-deploying EJBs while the server is still running.

Q) When should I use TxDataSource instead of Datasource?
If your application (or) environment meet the following criteria you should use
- uses JTA
- uses EJB container in web logic server to manage transactions.
- Includes multiple database updates with single transaction.
- Access multiple resources, such as database & JMS during transactions.
- Use same connection pool on multiple servers.

Q) Clustering
In J2ee container can be distributed, a distributed container consist of number of JVM’s running on one are more host machines. In this setup, application components can be deployed on a number of JVM’s. Subject to the type of loading strategy and the type of the component the container can distributed the load of incoming request to one of these JVM’s.

0 comments:

Post a Comment