JavaBeat FAQs
Sponsors
JAVABEAT
Home
Articles
Tips
QnA
Forums
FAQs Topics Books Topic
Java Java Books
Struts Struts Books
Spring Spring Books
Hibernate Hibernate Books
JBoss Seam Seam Books
J2EE J2EE Books
EJB EJB Books
JSF JSF Books
Servlets Servlets Books
JDBC JDBC Books
RMI RMI Books
JMS JMS Books
JNI JNI Books
Design Patterns Patterns Books
Exception Exception Books
Apache Ant Ant Books
Groovy
Cobertura
Quartz

Enterprise Java Beans(EJB) Interview Questions

EJB FAQs - 1 | EJB FAQs - 2 | EJB FAQs - 3 | EJB FAQs - 4 | EJB FAQs - 5 | EJB FAQs - 6 | EJB FAQs - 7 | EJB FAQs - 8 | EJB FAQs - 9 | EJB FAQs - 10 | EJB FAQs - 11 | EJB FAQs - 12

41) When should I use bean-managed transactions instead of specifying transaction information in the deployment descriptor?
 

The Sun J2EE EJB Guide says like this:

Although beans with container-managed transactions require less coding, they have one limitation: When a method is executing, it can be associated with either a single transaction or no transaction at all. If this limitation will make coding your session bean difficult, you should consider using bean-managed transactions.

The following pseudo-code illustrates the kind of fine-grained control you can obtain with bean-managed transactions. By checking various conditions, the pseudo-code decides whether to start and stop different transactions within the business method.

begin transaction
...
update table-a
...
if (condition-x)
   commit transaction
else if (condition-y)
   update table-b
   commit transaction
else
   rollback transaction
   begin transaction
   update table-c
   commit transaction
...

I think what it means is there are some limitations in j2ee transaction support. In a container managed situation, nested or multiple transactions are not allowed within a method. if a biz method needs those features you need to go for bean managed transactions.

42) How do I automatically generate primary keys?
 

A common way to do it is to use a stateless session bean to retrieve the ID that you wish to use as the primary key. This stateless session bean can then execute an Oracle sequencer or procedure etc. to retrieve the ID value used as the primary key.

43) How is the passivation of Entity beans Managed?
 

The passivation of Entity beans is managed by the container. To passivate an instance, the container first invokes the ejbStore() method for synchronizing the database with the bean instance, then the container invokes the ejbPassivate() method. It will then return the bean instance back to the pooled state. (Every bean has an instance pool.)

There are two ways for transitioning an entity bean from the ready to the pooled state, by using the ejbPassivate() or ejbRemove() method. The container uses ejbPassivate() to disassociate the bean instance from the entity object identity, and uses ejbRemove() to remove the entity object.

When the instance is put back into the pool, it is no longer associated with an entity object identity. The container can now assign the instance to any entity object within the same entity bean home.

A bean instance in the pool can be removed by using unsetEntityContext().

44) To complete a transaction, which Transaction Attributes or Isolation Level should be used for a stateless session bean?
 

[For example, I have a method transfer which transfers funds from one account to another account.]

Vague question. Is the Session bean doing the DB work? I'll assume no.

Let's say AtmEJB is a Session bean with the transfer method. Let's say AccountEJB is an Entity bean.

Step 1:

When the client invokes the transfer method you want that to be the transaction; i.e. "the transfer transaction". therefore you need to set the tx attribute of transfer to something that will make the container start a tx at the beginning of transfer and terminate it at the end of transfer. RequiresNew might be a good choice but you need to look at all your use cases not just this one.

Step 2:

The AccountEJB methods invoked from the transfer method need to have a tx attribute that allows them to be part of an ongoing tx. That means that deposit and withdraw cannot be RequiresNew! (that would suspend the transfer tx and run in its own tx). Look at the spec for these: there are 3 that meets the criteria for deposit and withdraw in the transfer use case. Which one to use? What are the other use cases in which deposit and withdraw will be called? Find one that works for each one.

45) Explain the different Transaction Attributes and Isolation Levels with reference to a scenario.
 

The Enterprise JavaBeans model supports six different transaction rules:

·         TX_BEAN_MANAGED. The TX_BEAN_MANAGED setting indicates that the enterprise bean manually manages its own transaction control. EJB supports manual transaction demarcation using the Java Transaction API. This is very tricky and should not be attempted without a really good reason.

·         TX_NOT_SUPPORTED. The TX_NOT_SUPPORTED setting indicates that the enterprise bean cannot execute within the context of a transaction. If a client (i.e., whatever called the method-either a remote client or another enterprise bean) has a transaction when it calls the enterprise bean, the container suspends the transaction for the duration of the method call.

·         TX_SUPPORTS. The TX_SUPPORTS setting indicates that the enterprise bean can run with or without a transaction context. If a client has a transaction when it calls the enterprise bean, the method will join the client's transaction context. If the client does not have a transaction, the method will run without a transaction.

·         TX_REQUIRED. The TX_REQUIRED setting indicates that the enterprise bean must execute within the context of a transaction. If a client has a transaction when it calls the enterprise bean, the method will join the client's transaction context. If the client does not have a transaction, the container automatically starts a new transaction for the method. Attributes

·         TX_REQUIRES_NEW. The TX_REQUIRES_NEW setting indicates that the enterprise bean must execute within the context of a new transaction. The container always starts a new transaction for the method. If the client has a transaction when it calls the enterprise bean, the container suspends the client's transaction for the duration of the method call.

TX_MANDATORY. The TX_MANDATORY setting indicates that the enterprise bean must always execute within the context of the client's transaction. If the client does not have a transaction when it calls the enterprise bean, the container throws the TransactionRequired exception and the request fails.

46) What is the most efficient approach for integrating EJB with JSP? Should the EJBs be invoked directly from within JSP scriptlets? Should the access take place from within Java beans? Or is it best to use custom tags for this purpose?
 

JSP scriptlet code should be minimal. Invoking EJB code directly on a JSP page results in many lines of code on your JSP page, including try...catch blocks to catch naming and finding exceptions.

Using a standard JavaBean as an intermediary between the JSP page and EJB server cuts down on the amount of code needed to add to a JSP page, and promotes reuse. The JavaBean should be a simple wrapper around the EJB you are accessing.

If you use a standard JavaBean you could also use the jsp:useBean tag to setup EJB parameters, such as the server URL and server security parameters.

Custom tags are also an option. However, they require a lot more coding than a simple JavaBean wrapper. The point should be to rewrite as little code as possible while at the same time keeping the JSP scriptlet content as light as possible.

47) How do you get a JDBC database registered with a JNDI name so that it can be accessed from an EJB?
 

The short answer is that it depends on which container you're using to some extent. The one thing that (should be) common in EJB 1.1 containers is that the ejb-jar.xml file's entry for that bean needs to contain a 'resource-ref' stanza, like so:

<resource-ref>
  <res-ref-name>jdbc/LocalDB2<res-ref-name>
  <res-type>javax.sql.DataSource<res-type>
  <res-auth>Container<res-auth>
<resource-ref>

The res-ref-name is the most interesting part. This is the JNDI name relative to the java:comp/env namespace. Hence, to get this connection you'd do (in your bean):

  Context context = new InitialContext();
  DataSource source = context.lookup("java:comp/env/jdbc/LocalDB2");

which gives you a DataSource that you can call getConnection on.

The other half of this is container specific and done at deployment time by a 'Deployer' or 'Assembler' (to use the rolenames specified by the EJB spec.) This can work very differently from one container to the next, but here are a couple of (abbreviated) examples.

With Weblogic 5.1, you must define a connection pool in weblogic.properties, then edit the weblogic specific deployment descriptor (using the EJB Deployment tool) to associate the resource-ref specified in ejb-jar.xml with that connection pool.

With Inprise Application Server 4.0, all of the parameters for the connection (JDBC driver, connection URL, etc.) are specified in the inprise specific deployment descriptor (also editable via their deployment tool).

Other servers will have other ways of associating the resource-ref with a pre-defined connection pool.

48) How to manage fields that can have null values in a container-managed Entity bean?
 

First of all, let's just set up a typical scenario:

You are developing a product which allows a bank to sign up new customers online. You have done analysis and design and settled on having two tables: 'users' and 'account' (let's keep it simple). Each "user" will have a corresponding "account". The foreign key between the two will be the "account number".

So, for the 'users' table, you have the following fields: firstName, lastName, userId, password, and acctNum. When this table is created in the database, it is empty. Now you must relate your EJB code to this table for persistence. For simplicity sake I will leave out the Session bean (which I would use to talk to my Entity bean), the Entity bean primary key class, and the home and remote interfaces.

We have the UserBean:

public class UserBean implements javax.ejb.EntityBean {
  public String firstName = null;
  public String lastName  = null;
  public String userId    = null;
  public String password  = null;
  public long   acctNum   = -1;
 
/**
 * Called by the container after the UserHome.create() is called
 */
  public void ejbCreate(String userId, String password, long acctNum) {
  this.userId   = userId;
  this.password = password;
  this.acctNum  = acctNum;
  }
...
...
  public void setUserData(UserData data) throws RemoteExeption, UserDataException {
    this.firstName = data.getFirstName();
    this.lastName  = data.getLastName();
  }
...
...
}

Now, assuming you have the User (remote interface class), UserHome (home interface class), UserPK (primary key class) already done, you need to create the bean's deployment descriptor. Inside the deployment descriptor, you must specify the database table, 'users', which this bean will map to. Also, you must specify which fields from your bean map to which fields in the 'users' database table. (This is how the container knows which fields to persist between your bean and the database table.) Now assuming all code compiles and you have an EJB server up and running and you have deployed your bean, all you need to do is write a client (I would use a client to access a session bean, say 'CustomerSession', which would talk to my entity bean) to create a new user and pass in the userId, password and acctNum values, which will create the new user in the database.

Notice the fields in the UserBean will now be set, but the firstName and lastName fields will still be set to null. These fields will still be empty in the database and will not change until these fields are set in the bean, since it is persisted. Now, call the setUserData(UserData data) method for setting the firstName and lastName, and these fields will now be set in the database and no longer be null. The container will handle the persistence of any fields which are set to null, just as it will handle any fields which are set to some meaningful value.

49) How can I debug my EJB applications?
 

This depends upon which EJB Container you are using.

Borland's JBuilder 3.5, Foundation Edition allows you to debug any Java 2 application, including the Inprise Application Server, WebLogic Server and J2EE Reference implementation. You can download it free from www.borland.com/jbuilder.

There are other IDE's out there including NetBeans/Forte www.sun.com/forte/ffj/ce/ that can also debug EJB.

50) How can an applet talk directly with EJB?
 

An applet must use the same procedure as any other Java class: it must use JNDI to locate the EJB Home Interface, then use RMI to talk with the Home Interface as well as the EJB itself.

This means that the J2EE and/or JNDI and/or RMI classes need to be present in the applet's Java Virtual Machine. The easiest way to assure this is to use the latest Java Plug-in. Netscape 6, aka Mozilla, ships with the Java Plug-in. Other browsers have various problems with RMI and JNDI classes that are beyond the scope of this answer.

Note, however, that it is not recommended to use EJB directly from applets, in part due to compatibility issues. Instead, you can use Servlets inside the application server to provide an HTML front-end that is assured to work on a much larger base of clients.

Bookmark This Page : | | | | | | | | | | |
Related Articles
Liferay Portal Enterprise Intranets
ZK Developer’s Guide : Online Media Library
The BIRT Environment and Your First Report
AJAX - The Complete Reference
The Java 6.0 Compiler API
Spring Web Flow - Introduction
Introduction to Spring Web Framework
Integrating Struts With Spring
What's new in Struts 2.0? - Struts 2.0 Framework
Introductiion to Jakarta Struts
more articles
java6 ejb3 jsf hibernate eclipse ajax groovy spring seam java struts webservice j2me guice java5 jca tapestry soa linux ria

Sponsors
Webmaster Hosting Forum
Java Jobs
Latest in DLinks
http://javawave.blogspot.com/2008/04/quartz-job-scheduler-part-ii-example.html
Quartz Job Scheduler -- Part 1 (Setting up development project in Netbeans 6.1 beta)
Flex Messaging with BEA Workshop Studio
SOA and Virtualization: How do They Fit Together?
Introduction to Enterprise Portals - Why they Benefit IT and the Business
BEA WebLogic Operations Control: Application Virtualization for Enterprise Java
Best Practices for Building Production Quality EAR Files
BEA's SOA Reference Architecture - A Foundation for Business Agility
Blueprint for Successful SOA Integration
Guardian - What a tool!

JavaBeat Media (2004-2008), India
javabeat home | About Us
our network : opensource softwares
Copyright © 2007 JavaBeat