Tuesday, August 17, 2010

EJB interview questions



EJB Questions

Q: What is the J2EE?
The J2EE is a set of coordinated specifications and practices that together enable solutions for developing, deploying and managing multi-tier server-centric applications.

Q) What is enterprise java bean? Why ejb?
A) It’s a collection of java classes and xml descriptor files bundled together as a unit. The java classes must provide certain rules and call back methods as per ejb specifications.
When the application is so complex and requires certain enterprise level services such as concurrency, scalability, transaction services, resource pooling, security, fail-over, load-balancing ejb is the right choice.

Q) New in EJB 2.1?
 Message-driven beans (MDBs): can now accept messages from sources other than JMS.
 EJB query language (EJB-QL): many new functions are added to this language: ORDER BY, AVG, MIN, MAX, SUM, COUNT, and MOD.
 Support for Web services: stateless session beans can be invoked over SOAP/HTTP. Also, an EJB can easily access a Web service using the new service reference.
 EJB timer service: a new event-based mechanism for invoking EJBs at specific times.
 Many small changes: support for the latest versions of Java specifications, XML schema, and message destinations.

Q) Application server & Web server
 A.S is a generalized server for running more than one application like ejb, rmi, jsp and servlets.
 W.S 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.
 W.S understands and supports only HTTP protocol whereas an Application Server supports HTTP, TCP/IP and many more protocols.
 A.S manage transactions, security, persistence, clustering, caching, 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) What does Container contain?
A) 1. Support for Transaction Management, 2. Support for Security 3. Support for Persistence 4. Support for management of multiple instances (Instance passivation, Instance Pooling, Database connection pooling)
5. Life Cycle Management

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.

Q) Statefull Session Bean & Stateless Session Bean
Stateless Session Bean Stateful Session Bean
Stateless session bean these are single request business process is one that does not require state to be maintained across method invocation. Stateless session bean cannot hold the state. 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.
There should be one and only one create method that to without any argument in the home interface. There can be one or more create methods with or without arguments in the Home Interface.
Stateless session bean instance can be pooled. Therefore “n” number of beans can cater to n+1 number of clients. Statefull session bean do not have pooling concept. Stateful bean will be given individual copy for every user.
Stateless bean will not be destroyed after client has gone. Stateful bean will be destroyed once the client has gone (or after session time out)
If the business last only for a single method call, S.S.B are suitable If the business process spans multiple invocations there by requiring a conversational then S.S.B will be ideal choice.
Stateless session bean cannot have instance variable Stateful session bean will have instance variable and state is maintained in these instance variables
EjbRemove() method does not destroy the bean , it remains in the pooled state. Stateful bean can be destroyed by calling the ejbRemove() method



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 database. In entity bean deployment descriptor you specify which fields that the container should manage. The transactions 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) 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) Diff MDB & Stateless Session beans?
- MDB’s process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls.
- MDB have no H.I / R.I, and therefore cannot be directly accessed by internal or external clients. Clients interact with MDB’s only indirectly, by sending a message to a JMS Queue or Topic.
- Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary
-The Container maintains the entire lifecycle of a MDB; instances cannot be created or removed as a result of client requests or other API calls.

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) When to choose 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 database.
 S.B for application logic.

Q) When to choose CMP & BMP?
CMP is used when the persistent 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 persistence is used when there is no “one to one” mapping of the table and a complex query retrieving 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) How do Stateful Session beans maintain consistency across transaction updates?
A) S.S.B maintain data consistency by updating their fields each time a transaction is committed. To keep informed of changes in transation status, a S.S.B implements the SessionSynchronization interface. Container then calls methods of this interface as it initiates and completes transactions involving the bean.

Q) Can't stateful session beans persistent? Is it possible to maintain persistence temporarily in stateful sessionbeans?
A) Session beans are not designed to be persistent, whether stateful or stateless. A stateful session bean instance typically can't survive system failures and other destructive events.
Yes, it is possible using Handle.

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) 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?
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 develop an Entity Bean without implementing the create() method in the home interface?
As per the specifications, there can be 'ZERO' or 'MORE' create() methods defined in an Entity Bean. In cases where create() method is not provided, the only way to access the bean is by knowing its primary key, and by acquiring a handle to it by using its corresponding finder method. In those cases, you can create an instance of a bean based on the data present in the table. All one needs to know is the primary key of that table. i.e. a set a columns that uniquely identify a single row in that table. Once this is known, one can use the 'getPrimaryKey()' to get a remote reference to that bean, which can further be used to invoke business methods.

Q) How do you determine whether two entity beans are the same?
A) By invoking the EntityBean.isIdentical method. This method should be implemented by the entity bean developer to determine when two references are to the same object.

Q) How can you capture if findBy method returns more than one row?
A) If finder method returns more than one row, create or instantiate an object (which has instance variable equal to number of columns to be stored) each time and add the object to vector that stores. Vector stores only the memory address not object reference. So every time when you instantiate and store object into vector a separate memory address will be allocated and the same is stored in the vector.

Q) Diff Context, InitialContext & SessionContext & EntityContext
javax.naming.Context is an interface that provides methods for binding a name to an object. It's much like the RMI Naming.bind() method.

javax.naming.InitialContext is a Context and provides implementation for methods available in the Context interface.

Where as SessionContext is an EJBContext object that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container.

There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean for the purpose of the EntityBean accessing the container details. In general, the EJBContext (SessionContext and EntityContext), AppletContext and ServletContext help the corresponding Java objects in knowing about its 'context' [environment in which they run], and to access particular information and/or service. Where as, the javax.naming.Context is for the purpose of 'NAMING' [by the way of referring to] an object.

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 you use Bean-Managed Persistence(BMP), map the bean to tables manually. Consider applying the DAO design pattern to accomplish this.
If you 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(SessionContext 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, i.e. 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, and 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 requests.

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) 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) 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) What is the need of Remote and Home interface. Why cant it be in one?
The home interface is your way to communicate with the container, that is who is responsible of creating, locating even removing one or more beans. The remote interface is your link to the bean, that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and beans) and you need two different interfaces for accessing to both of them.

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




Q) Session Bean Example

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) Entity Bean Example

Home.java (Home Interface)
package test;

public interface Home extends javax.ejb.EJBHome {
public String hello() throws RemoteException;
public int add(int a, int b) throws RemoteException;
public HomeObj findByPrimaryKey(String a) throws RemoteException, FinderException;
}

HelloObj.java (Remote Interface)
package test;

public interface HelloObj extends javax.ejb.EJBObject {
}

HelloBean.java (Bean class)
package test;
import javax.ejb.*;

public class HelloBean extends com.caucho.ejb.AbstractEntityBean {
public String ejbHomeHello()
{
return "Hello, world";
}

public int ejbHomeAdd(int a, int b)
{
return a + b;
}

public String ejbFindByPrimaryKey(String key) throws FinderException
{
throw new FinderException("no children");
}
}

Client
package test.entity.home;
import javax.naming.*;

public class HomeServlet extends GenericServlet {
Home home;

public void init() throws ServletException
{
try {
Context env = (Context) new InitialContext().lookup("java:comp/env");
home = (Home) env.lookup("ejb/home");
} catch (Exception e) {
throw new ServletException(e);
}
}

public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException
{
PrintWriter pw = res.getWriter();
try {
pw.println("message: " + home.hello() + "");
pw.println("1 + 3 = " + home.add(1, 3) + "");
pw.println("7 + 1 = " + home.add(7, 1) + "");
} catch (Exception e) {
throw new ServletException(e);
}
}
}



Q) How do you configure a session bean for bean-managed transactions?
A) By set transaction-attribute in the xml file or in the deployment descriptor.

No comments: