Search

Complete reference to EJB - Enterprise Java Beans interview questions basic to advanced level : SE to Team Lead level Part - 3

application functionality such as transaction support,

17). What are the Interfaces need to create to implement Session Bean with Exmaple?

Session bean class (CartBean) 
Home interface (CartHome) 
Remote interface (Cart) 

Session bean class (CartBean) : 
public class CartBean implements SessionBean { 

String customerName; 
String customerId; 
Vector contents; 

public void ejbCreate(String person) 
throws CreateException { 

if (person == null) { 
throw new CreateException("Null person not allowed."); 
} 
else { 
customerName = person; 
} 

customerId = "0"; 
contents = new Vector(); 
} 

public void ejbCreate(String person, String id) 
throws CreateException { 

if (person == null) { 
throw new CreateException("Null person not allowed."); 
} 
else { 
customerName = person; 
} 

IdVerifier idChecker = new IdVerifier(); 
if (idChecker.validate(id)) { 
customerId = id; 
} 
else { 
throw new CreateException("Invalid id: "+ id); 
} 

contents = new Vector(); 
} 

public void addBook(String title) { 
contents.addElement(title); 
} 

public void removeBook(String title) throws BookException { 

boolean result = contents.removeElement(title); 
if (result == false) { 
throw new BookException(title + "not in cart."); 
} 
} 

public Vector getContents() { 
return contents; 
} 

public CartBean() {} 
public void ejbRemove() {} 
public void ejbActivate() {} 
public void ejbPassivate() {} 
public void setSessionContext(SessionContext sc) {} 

} 


Home Interface: 
public interface CartHome extends EJBHome { 
Cart create(String person) throws 
RemoteException, CreateException; 
Cart create(String person, String id) throws 
RemoteException, CreateException; 
} 

The signatures of the ejbCreate and create methods are similar, but differ in important ways. The rules for defining the signatures of the create methods of a home interface follow. 

The number and types of arguments in a create method must match those of its corresponding ejbCreate method. 
The arguments and return type of the create method must be valid RMI types. 
A create method returns the remote interface type of the enterprise bean. (But an ejbCreate method returns void.) 
The throws clause of the create method must include the java.rmi.RemoteException and the javax.ejb.CreateException 

Remote Interface : 
public interface Cart extends EJBObject { 

public void addBook(String title) throws RemoteException; 
public void removeBook(String title) throws 
BookException, RemoteException; 
public Vector getContents() throws RemoteException; 
} 
The method definitions in a remote interface must follow these rules: 

Each method in the remote interface must match a method implemented in the enterprise bean class. 
The signatures of the methods in the remote interface must be identical to the signatures of the corresponding methods in the enterprise bean class. 
The arguments and return values must be valid RMI types. 
The throws clause must include the java.rmi.RemoteEx
18). How many EJB Objects are created for a Bean?
For a Session bean - one EJB object for one bean instance. For entity bean it depends, if 2 users are accessing one row at time then one EJB object is used for both the beans other wise for each bean one EJB object.
19). What are the parameters must follow for Session Bean ?
It implements the SessionBean interface. 
The class is defined as public. 
The class cannot be defined as abstract or final. 
It implements one or more ejbCreate methods. 
It implements the business methods. 
It contains a public constructor with no parameters. 
It must not define the finalize method.
20).When you will chose Stateful session bean and Stateless session bean?
Stateful session beans are used when there is converstional state and when there is a need of temporary storage 

Stateless session bean are used when there is no conversational state and when session bean has to be used only for database access
21). What is the difference between Stateful session bean and Stateless session bean?
1.    A stateful session beans can keep data between client accesses. wheras a stateless session bean cannot.
2) A stateful seesion bean contain the state of client after seesion is expired. whereas a stateless bwan cnanot.
3) A stateful session beans use the bean of pools for client application n after use them it return the bean in the pool. whereas a stateless session bean cannot.
22). What are the callbacks method in Session Bean ?
public void ejbCreate() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
23). How is Stateful Session bean maintain their states with client?
When a client refers to a Stateful Session object reference, all calls are directed to the same object on the EJB container. The container does not require client identity information or any cookie object to use the correct object.
This means that for a client to ensure that calls are directed to the same object on the container, all it has to do is to use same reference for every call.

For example the following holds for all stateful session beans:


StatefulHome sfh = ...//get home interface for stateful bean
Stateful bean1 = sfh.create();
Stateful bean2 = sfh.create();
if (bean1.isIdentical(bean1)){} //this is true!
if (bean1.isIdentical(bean2)){} //this is false!

//Note that the second test would evaluate to true for stateless beans

Thus, if you're calling a Stateful Session Bean from a servlet, your servlet need to keep the reference to the remote object in the HttpSession object between client calls for you to be 
able to direct calls to the same object on the container.
Likewise, if you're calling from an application, you only obtain the reference to the bean once and reuse the object throughout the application session.
24).  What is the free pool?
The free pool is a data 
structure the EJB container uses to cache anonymous instances of a given bean type. The free pool improves performance by reusing objects and skipping container callbacks when it can.
25). Without home and remote interfaces cant we implement ejb?
Was just reading about EJB 3.0. I suppose with EJB 3.0, Home interface is absolutely gone and implementing Business Interface is not mandatory. All enterprise beans in EJB 3.0 are just POJO (Plain Old Java Object) with appropriate annotations.
26). When are stateless EJBs passivated?
Stateless ejbs are never passivated. Since stateless ejbs do not have state, there is no need to passivate them. They are put back into the free pool after each method call so they will be available to service other requests.
27). Is method overloading allowed in EJB?
Yes you can overload methods Should synchronization primitives be used on bean methods? - No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime.
28). What is handle and why it is used in EJB?
The handle mechanism allows a client application to maintain a reference to an EJB object. A handle object may be obtained by calling the getHandle() method on the reference to an EJB object. The main interest is that the handle class implements java.io.serializable interface, which means that a handle may be serialized. This allows the client to store the handle, or to pass it to another process. The handle may then be deserialized and used to obtain the reference to the EJB object, by calling the getEJBObject() method.

Handles on session bean objects are valid until the session bean object exists, i.e. their life time is limited to that of the client. Handles on entity bean objects are valid during the complete life time of the entity bean object; this means that such handles may be used by different clients and stored for a long time; the EJB server holding the entity bean objects may be stopped and restarted, the handle will still be valid.


If we consider the entity bean object of the example above (a2), the way to obtain a handle on this object is the following (the handle class is defined in the javax.ejb package):

Handle h = a2.getHandle();The handle object may then be serialized and stored in a file:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("handlefile"));
out.writeObject(h);
out.close();
Then, a client can read the handle, and retrieve the referenced object:

ObjectInputStream in = new ObjectInputStream(new FileInputStream("handlefile"));
Handle h = (Handle) in.readObject();
Account a = (Account)PortableRemoteObject.narrow(h.getEJBObject(),
Account.class);
The EJB Specification allows the client to obtain a handle for the home interface. This allows the client to store a reference to an entity bean's home interface in stable storage. The client code must use the javax.rmi.PortableRemoteObject.narrow(...) method to convert the result of the getEJBHome() method invoked on a handle to the home interface type
29). Implement Local and Remote Interfaces in EJB?
Remote BeansThe EJB 1.1 specification defines all EJBs as remote objects. This means that every time you make a call to an EJB, you are making a remote call. This means that there is considerable overhead to each EJB call, and hence performance implications. To combat this, server vendors invented a way of circumventing the remote calls to some degree. Oracle's solution with OC4J was the pass-by-reference setting, which determined whether EJB objects were communicated by reference to the object, or whether the whole object had to be passed to the client.

An EJB has a remote interface and a home interface, with the exception of MessageDrivenBeans. The remote interface extends the interface javax.ejb.EJBObject and the home interface extends the interface javax.ejb.EJBHome. The EJB is accessible from any client, in any JVM, provided they have the proper authorization.

For example, the Home and Remote interfaces of an EJB called EMP may look like this.

Remote:

public interface Emp extends EJBObject
{
long getEmpno() throws RemoteException;
void setEmpno(long newDeptno) throws RemoteException;
String getEname() throws RemoteException;
void setEname(String newDname) throws RemoteException;

Home:

public interface DeptHome extends EJBHome
{
public Emp create() throws RemoteException, CreateException;
public Dept findByPrimaryKey(DeptPK primaryKey) throws RemoteException, FinderException;

Note that both the home and the remote interface throw a RemoteException in all of their method definitions. The ejb-jar.xml deployment descriptor for these EJBs would look something like the snippets below:

<entity>
<ejb-name>Emp</ejb-name>
<home>ejb.cmplocal.EmpHome</home>
<remote>ejb.cmplocal.Emp</remote>
<ejb-class>ejb.cmplocal.EmpBean</ejb-class>
.
.
.

Local BeansThe EJB 2.0 specification standardize a means of making local connections to EJBs with Local Interfaces.

For an EJB to be classed as a local EJB, it must implement the local versions of the home and remote interfaces, javax.ejb.EJBLocalObject for the Home interface, and javax.ejb.EJBLocalHome. For a client to call the Local interface, they must be running in the same JVM as the JVM that the EJB exists in. This means that not only an EJB can call a local EJB , Servlets or JSPs can also call the EJB via it's local interface if they are packaged together as part of same application.

For example, the LocalHome and Local interfaces of an EJB called EMP may look like this.

Local:

public interface Emp extends EJBLocalObject
{
long getEmpno();
void setEmpno(long newEmpno);
String getEname();
void setEname(String newEname);
LocalHome:

public interface EmpHome extends EJBLocalHome
{
public Emp create() throws CreateException;
public Emp findByPrimaryKey(EmpPK primaryKey) throws FinderException;
The ejb-jar.xml deployment descriptor for these EJBs would look something like the snippets below:

<entity>
<ejb-name>Emp</ejb-name>
<local-home>ejb.cmplocal.EmpHome</local-home>
<local>ejb.cmplocal.Emp</local>
<ejb-class>ejb.cmplocal.EmpBean</ejb-class>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>Emp</abstract-schema-name>

Note that now the local interfaces no longer throw the RemoteException, showing that they are not remotely called methods. Also, the XML contains different elements. There is now a local-home and a local tag. Also we are declaring that this is an EJB 2.x bean, using the cmp-version tag.

Calling Local BeansCalling a local bean from Java code is very simple, and very similar to using a remote bean. The code to call a remote bean is shown below.

try
{
Context ctx = new InitialContext();
Object o = ctx.lookup("Emp");
EmpHome empHome = PortableRemoteObject.narrow(o, EmpHome.class)
return empHome.findByDeptno(getDeptno());
}
catch (RemoteException r)
{
System.err.println("Error loading Employees(Remote): " + r.getMessage()); return null;
}
catch (NamingException n)
{
System.err.println("Error loading Employees(Naming): " + n.getMessage());
return null;
}
catch (FinderException f)
{
System.err.println("Error loading Employees(Finder): " + f.getMessage());
return null;
}
The code for a local bean is similar, but we no longer have to worry about the PortableRemoteObject, as the bean is no longer remote.

try
{
Context ctx = new InitialContext();
Object o = ctx.lookup("java:comp/env/LocalEmp");
EmpHome empHome = (EmpHome)o;
return empHome.findByDeptno(getDeptno());
}
catch (NamingException n)
{
System.err.println("Error loading Employees(Naming): " + n.getMessage());
return null;
}
catch (FinderException f)
{
System.err.println("Error loading Employees(Finder): " + f.getMessage());
return null;
}

As you can see, the local bean has to lookup the EJB slightly differently, even though they are running in the same container. Also, there is no RemoteException thrown by the find or the create methods, so the exception does not have to be caught.

There is one more difference, and that is in the ejb-jar.xml deployment descriptor. For an EJB to look up a local EJB, it must point to the correct location using an <ejb-local-ref> tag. If this is not used, the container will not be able to find the bean. For each EJB that needs to use the local EJB, the XML below must be in the deployment descriptor.

<entity>
<ejb-name>Dept</ejb-name>
.
.
.
<ejb-local-ref>
<ejb-ref-name>LocalEmp</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>ejb.cmplocal.EmpHome</local-home>
<local>ejb.cmplocal.Emp</local>
<ejb-link>Emp</ejb-link>
</ejb-local-ref>
</entity>
This example will allow the EJB Dept to call the local EJB Emp using the name LocalEmp. This is required because EJBs can have both local and remote interfaces, and to call the EJB Emp via it's remote interface the EJB Dept would look up the name Emp rather than the local reference LocalHome.
30). How can I call one EJB from inside of another EJB?
In case of Remote :
EJBs can be clients of other EJBs. It just works. Really. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference.
For Example : Context ctx = new InitialContext();
//get Home interface of bean
//narrow -retype
EmpHome lhome = (EmpHome ) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("java:comp/env/LocalEmp"), EmpHome .class);

//get remote interface
Emplbean = lhome.create();
//now you can call bussiness method on remote interface like
lbean.doSomething()

Incase of Local : but we no longer have to worry about the PortableRemoteObject, as the bean is no longer remote

Context ctx = new InitialContext();
Object o = ctx.lookup("java:comp/env/LocalEmp");
EmpHome empHome = (EmpHome)o;
31). What is the difference between Message Driven Beans and Stateless Session 
       beans
In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways:

Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls.

Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic.

Note: 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 message-driven bean; instances cannot be created or removed as a result of client requests or other API calls
32). Can you control when passivation occurs?
The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to control passivation.

The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic.

Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls.

Taken from the WebLogic 6.0 DTD -"The passivation-strategy can be either "default" or "transaction". With the default setting the container will attempt to keep a working set of beans in the cache. With the "transaction" setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).
33). How to call any EJB from a servlet/JSP/Java Client?
Context ctx = new InitialContext();

//get Home interface of bean
//narrow -retype
BeanHome lhome = (BeanHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("cz.train.Bean"), BeanHome.class);

//get remote interface
Bean lbean = lhome.create();

//now you can call bussiness method on remote interface like
lbean.doSomething()
34). Can the primary key in the entity bean be a Java primitive type such as int?
The primary key can't be a primitive type--use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive)
35). What are the methods of Entity Bean?
An entity bean consists of 4 groups of methods:

1. create methods: To create a new instance of a CMP entity bean, and therefore insert data into the database, the create() method on the bean's home interface must be invoked. They look like this: EntityBeanClass ejbCreateXXX(parameters), where EntityBeanClass is an Entity Bean you are trying to instantiate, ejbCreateXXX(parameters) methods are used for creating Entity Bean instances according to the parameters specified and to some programmer-defined conditions.

A bean's home interface may declare zero or more create() methods, each of which must have corresponding ejbCreate() and ejbPostCreate() methods in the bean class. These creation methods are linked at run time, so that when a create() method is invoked on the home interface, the container delegates the invocation to the corresponding ejbCreate() and ejbPostCreate() methods on the bean class.

2. finder methods: The methods in the home interface that begin with "find" are called the find methods. These are used to query the EJB server for specific entity beans, based on the name of the method and arguments passed. Unfortunately, there is no standard query language defined for find methods, so each vendor will implement the find method differently. In CMP entity beans, the find methods are not implemented with matching methods in the bean class; containers implement them when the bean is deployed in a vendor specific manner. The deployer will use vendor specific tools to tell the container how a particular find method should behave. Some vendors will use object-relational mapping tools to define the behavior of a find method while others will simply require the deployer to enter the appropriate SQL command.

There are two basic kinds of find methods: single-entity and multi-entity. Single-entity find methods return a remote reference to the one specific entity bean that matches the find request. If no entity beans are found, the method throws an ObjectNotFoundException . Every entity bean must define the single-entity find method with the method name findByPrimaryKey(), which takes the bean's primary key type as an argument.

The multi-entity find methods return a collection ( Enumeration or Collection type) of entities that match the find request. If no entities are found, the multi-entity find returns an empty collection.

3. remove methods: These methods (you may have up to 2 remove methods, or don't have them at all) allow the client to physically remove Entity beans by specifying either Handle or a Primary Key for the Entity Bean.

4. home methods: These methods are designed and implemented by a developer, and EJB specification doesn't have any requirements for them except the need to throw a RemoteException is each home method.
36). What is the difference between Container-Managed Persistent (CMP) bean and Bean-Managed Persistent(BMP) ?
Container-managed persistence(CMP) beans are the simplest for the bean developer to create and the most difficult for the EJB server to support. This is because all the logic for synchronizing the bean's state with the database is handled automatically by the container. This means that the bean developer doesn't need to write any data access logic, while the EJB server is supposed to take care of all the persistence needs automatically. With CMP, the container manages the persistence of the entity bean. A CMP bean developer doesn't need to worry about JDBC code and transactions, because the Container performs database calls and transaction management instead of the programmer. Vendor tools are used to map the entity fields to the database and absolutely no database access code is written in the bean class. All table mapping is specified in the deployment descriptor. Otherwise, a BMP bean developer takes the load of linking an application and a database on his shoulders.

The bean-managed persistence (BMP) enterprise bean manages synchronizing its state with the database as directed by the container. The bean uses a database API to read and write its fields to the database, but the container tells it when to do each synchronization operation and manages the transactions for the bean automatically. Bean-managed persistence gives the bean developer the flexibility to perform persistence operations that are too complicated for the container or to use a data source that is not supported by the container.BMP beans are not 100% database-independent, because they may contain database-specific code, but CMP beans are unable to perform complicated DML (data manipulation language) statements. EJB 2.0 specification introduced some new ways of querying database (by using the EJB QL - query language).
37).Can Entity Beans have no create() methods?
Yes. In some cases the data is inserted NOT using Java application, so you may only need to retrieve the information, perform its processing, but not create your own information of this kind
38). What is bean managed transaction?
If a developer doesn't want a Container to manage transactions, it's possible to implement all database operations manually by writing the appropriate JDBC code. This often leads to productivity increase, but it makes an Entity Bean incompatible with some databases and it enlarges the amount of code to be written. All transaction management is explicitly performed by a developer.
39). What are transaction isolation levels in EJB?
1.    Transaction_read_uncommitted- Allows a method to read uncommitted data from a DB(fast but not wise).

2. Transaction_read_committed- Guarantees that the data you are getting has been committed.

3. Transaction_repeatable_read - Guarantees that all reads of the database will be the same during the transaction (good for read and update operations).

4. Transaction_serializable- All the transactions for resource are performed serial.
40). What is the difference between ejbCreate() and ejbPostCreate
The purpose of ejbPostCreate() is to perform clean-up database operations after SQL INSERTs (which occur when ejbCreate() is called) when working with CMP entity beans. ejbCreate() is called before database INSERT operations. You need to use ejbPostCreate() to define operations, like set a flag, after INSERT completes successfully.

When working with 
BMP entity beans, this is not necessary. You have full control over the entire process, so you can place all the necessary logic surrounding your INSERT statement directly in the ejbCreate() method.

Even if you are creating BMP entity beans, the recommendation would still be to include an empty ejbPostCreate() method. Although some application servers will not enforce it, the spec indicates that this placeholder should be there.
41).What is the difference between sessioncontext and entitycontext?
Since EnterpriseBeans live in a managed container,the container is free to call your EJB components methods at its leisure.

The container houses the information like current status of bean,security credentials of the user currently accessing the bean in one object is called EJBContext Object.

A context represents a way for beans to perform callbacks and modify their current status

SessionContext is EJB context for 
session bean

EntityContext is EJB context for entity bean

Message driven context is EJB context for message driven bean
42). What is the difference between ejbStore() and ejbLoad()?
ejbStore() will be called before ejbPassivate() and is used to store the object to persistent database.
ejbLoad() will be called before ejbActivate() and is used to retrieve the object from persistence datastore.
43). What is the difference between EAR, JAR and WAR file?
J2EE defines three types of archives:

1. 
Java Archives (JAR)—A JAR file encapsulates one or more Java

classes, a manifest, and a descriptor. JAR files are the lowest

level of archive. JAR files are used in J2EE for packaging EJBs

and client-side Java Applications.

2. Web Archives (WAR)—WAR files are similar to JAR files, except

that they are specifically for web applications made from

Servlets, JSPs, and supporting classes.

3. Enterprise Archives (EAR)—An EAR file contains all of the

components that make up a particular J2EE application.
44).How to implement an entity bean which the PrimaryKey is an autonumeric?
The EJB 2 Spec (10.8.3 - Special case: Unknown primary key class) says that in cases where the PrimaryKeys are generated automatically by the underlying database, thebean provider must declare the findByPrimaryKey method to return java.lang.Object and specify the Primary Key Class as java.lang.Object in the Deployment Descriptor.

When defining the Primary Key for the Enterprise Bean, the Deployer using the Container Provider's tools will typically add additional container-managed fields to the concrete subclass of theentity bean class.

In this case, the Container must generate the Primary Key value when the entity bean instance is created (and before ejbPostCreate is invoked on the instance.)
45). Is Decorator an EJB design pattern?
No. Decorator design pattern, is the one which exhibits very low level runtime polymorphism, for the specific and single object (Instance of the class), but not for atleast for a class. It is the stuff to add specific functionality to a single & pointed object and leaves others like it unmodified. It is having close similarities like aspect stuff, but not with EJB stuff.
46). What is lazy loading?
Lazy loading means not creating an object until the first time it is accessed. Lazy loading typically looks like this:

public class Example {
private Vector data = null;

public Vector getData() {
if (this.data == null) {
this.data = new Vector();
// Load data into vector ...
}
return this.data;
}
}

This technique is most useful when you have large hierarchies of objects (such as a product catalog). You can lazy-load subordinate objects as you navigate down the hierarchy, and thereby only creat objects when you need them.
47). What is Message Driven Bean?
An MDB is essentially a message consumer that can listen to a message destination or a message endpoint and gets activated when a message arrives. By design, MDBs are anonymous in nature and hence cannot be directly invoked by a client. The only way to invoke an MDB is to send a message to the destination or endpoint to which it is listening. As MDBs are stateless in nature and are not related to any specific client, they can be pooled for concurrent processing of messages.
48). What is CMR?

CMR is an acronym for Container Managed Relation-ships.
CMR, represented by the cmr fields in the deployment descriptor, which represents the relationship exists between different entities (entity beans), which are in turn exhibiting the database to the real world. The relationships are one-one, one-many, & many-many.
All the relations/ referential integrities will be managed by container, then the definition's in the deployment descriptor's are called as Container Managed Relationships (CMR)..

No comments:

Post a Comment