Home > Articles > Programming > Java

This chapter is from the book

Creating a Session Bean That Does Some Work

The main purpose of the HelloWorldSession example was to get you familiar with the overall structure of a session bean. Writing three different Java files for a single component seems overwhelming at first, but after you're used to it, it doesn't seem like such a big deal.

Now that you're familiar with the structure of a session bean, you can write a bean that does some work. Specifically, you can write a bean that retrieves data from a database. For this example, assume that you have an SQL table containing product codes and prices, created using the following SQL statement:

					
create table price
    (product_code varchar(10) not null primary key,
     price decimal(10,2) not null)

The Pricing session bean gives you a list of all valid product codes and can return the price for a specific code, as specified by the Remote interface shown in Listing 6.9.

Listing 6.9 Source Code for Pricing.java

package usingj2ee.pricing;

import java.rmi.*;
import javax.ejb.*;

/** Defines the methods you can call on a Pricing session */

public interface Pricing extends EJBObject
{

/** Returns all the available product codes */
    public String[] getProductCodes() throws RemoteException;

/** Returns the price for a specific product code */
    public double getPrice(String productCode)
        throws RemoteException, InvalidProductCodeException;

}

The Pricing session bean doesn't need to remember anything about a particular client, so it can be implemented as a stateless session bean. Thus, the PricingHome interface, shown in Listing 6.10, only needs a single create method.

Listing 6.10 Source Code for PricingHome.java

package usingj2ee.pricing;

import java.rmi.*;
import javax.ejb.*;

/** Defines the methods for creating a Pricing session */

public interface PricingHome extends EJBHome
{

/** Creates a Pricing session bean */
    public Pricing create() throws RemoteException, CreateException;

}

When a session bean needs to access a database connection, it usually allocates the connection in the setSessionContext method and releases the connection in the ejbRemove method. Of course, if you are holding onto a database connection, you must also be prepared to close it if the container calls ejbPassivate and make the connection again when the container calls ejbActivate.

You'll find that most EJB developers create a method to return a connection; that way you can change the way you get connections without affecting the various places where you need to create one. You should also use a DataSource object to create your connections. A DataSource makes it easy to change database drivers and to use a connection pool when necessary.

Listing 6.11 shows the PricingImpl implementation class for the Pricing session bean.

Listing 6.11 Source Code for PricingImpl.java

package usingj2ee.pricing;

import java.rmi.*;
import java.util.*;
import javax.ejb.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;

/** The implementation class for the Pricing bean */

public class PricingImpl implements SessionBean
{
/** The session context provided by the EJB container. A session bean must
    hold on to the context it is given. */

    private SessionContext context;

/** The database connection used by this session */

    private Connection conn;

/** An EJB must have a public, parameterless constructor */

    public PricingImpl()
    {
    }     

/** Called by the EJB container to set this session's context */

    public void setSessionContext(SessionContext aContext)
    {
        context = aContext;
    }

/** Called by the EJB container when a client calls the create() method in
    the Home interface */

    public void ejbCreate()
        throws CreateException
    {
        try
        {
// Allocate a database connection
            conn = getConnection();
        }
        catch (Exception exc)
        {
            throw new CreateException(
                "Unable to access database: "+exc.toString());
        }
    }

/** Called by the EJB container to tell this session bean that it is being
    suspended from use (it's being put to sleep). */

    public void ejbPassivate()
        throws EJBException
    {
        try
        {
// Shut down the current database connection
            conn.close();
            conn = null;
        }
        catch (Exception exc)
        {
            throw new EJBException("Unable to close database connection: "+
                exc.toString());
        }
    }     

/** Called by the EJB container to wake this session bean up after it
    has been put to sleep with the ejbPassivate method. */

    public void ejbActivate()
        throws EJBException
    {
        try
        {
// When the bean wakes back up, get a database connection again
            conn = getConnection();
        }
        catch (Exception exc)
        {
            throw new EJBException(
                "Unable to access database: "+exc.toString());
        }
    }

/** Called by the EJB container to tell this session bean that it has been
    removed, either because the client invoked the remove() method or the
    container has timed the session out. */     

    public void ejbRemove()
        throws EJBException
    {
        try
        {
// Shut down the current database connection
            conn.close();
            conn = null;
        }
        catch (Exception exc)
        {
            throw new EJBException("Unable to close database connection: "+
                exc.toString());
        }
    }

/** Returns a list of the available product codes */

    public String[] getProductCodes()
        throws EJBException
    {
        Statement s = null;

        try
        {
            s = conn.createStatement();     

            ResultSet results = s.executeQuery(
                "select product_code from price");

            Vector v = new Vector();

// Copy the results into a temporary vector
            while (results.next())
            {
                v.addElement(results.getString("product_code"));
            }

// Copy the vector into a string array
            String[] productCodes = new String[v.size()];
            v.copyInto(productCodes);     

            return productCodes;
        }
        catch (Exception exc)
        {
            throw new EJBException("Unable to get product codes: "+
                exc.toString());
        }
        finally
        {
// Close down the statement in a finally block to guarantee that it gets
// closed, whether an exception occurred or not

            try
            {
                s.close();
            }
            catch (Exception ignore)
            {
            }
        }
    }

/** Gets the price for a particular product code */

    public double getPrice(String productCode)
        throws EJBException, InvalidProductCodeException
    {
        PreparedStatement ps = null;
        try
        {
// It's always better to use a prepared statement than to try to insert
// a string directly into the query string. This way you don't have to
// worry if there's a quote in the product code

            ps = conn.prepareStatement(
                "select price from price where product_code = ?");     

// Store the product code in the prepared statement
            ps.setString(1, productCode);

            ResultSet results = ps.executeQuery();

// If there are any results, get the first one (there should only be one)
            if (results.next())
            {
                return results.getDouble("price");
            }
            else
            {
// Otherwise, if there were no results, this product code doesn't exist
                throw new InvalidProductCodeException(productCode);
            }
        }
        catch (SQLException exc)
        {
            throw new EJBException("Unable to get price: "+
                exc.toString());
        }
        finally
        {
// Close down the statement in a finally block to guarantee that it gets
// closed, whether an exception occurred or not
            try
            {
                ps.close();
            }
            catch (Exception ignore)
            {
            }
        }
    }     

    protected Connection getConnection()
        throws SQLException, NamingException
    {
// Get a reference to the naming service
        InitialContext context = new InitialContext();

// Get the data source for the pricing database
        DataSource ds = (DataSource) context.lookup(
            "java:comp/env/jdbc/PriceDB");

// Ask the data source to allocate a database connection
        return ds.getConnection();
    }
}     
					

The getConnection method in PricingImpl deserves some special attention. Notice that it uses JNDI (the naming service) to locate a data source named java:comp/env/jdbc/PriceDB. The prefix java:comp/env refers to the JNDI naming context for your session bean. When the session bean is deployed in an EJB container, the container sets up a naming context for the bean with various entries that are set up when you deploy the bean. The java:comp/env naming context lets you associate logical names with various resources. The idea is that when you write the bean, you don't need to know the exact name of a data source or Home interface to use it. When you deploy the bean into a container, you set up associations that link the names used by the bean to the actual resource name. This substantially improves the portability of the bean because it isn't tied to specific resource names.

When you deploy the Pricing bean, you must specify an alias name for jdbc/PriceDB. If you're using the Cloudscape database that comes with the J2EE SDK, this alias must be jdbc/Cloudscape. Otherwise, you must set up a data source in the EJB server that points to the database you want to work with. When you deploy the Pricing bean, you specify the name of the data source that jdbc/PriceDB refers to. Again, jdbc/PriceDB is a logical name. You can use the Pricing bean with many different databases just by changing the naming association when you deploy the bean.

If you are using a different data source, you can change it at deployment time. You can also set up a default.properties file containing information about various drivers and databases you want to use. For example, you can use the following default.properties file for an Oracle database:

					
jdbc.drivers=oracle.jdbc.driver.OracleDriver
jdbc.datasources=jdbc/Oracle|jdbc:oracle:thin:@localhost:1521:orcl

After you set up this alternate data source, which is called jdbc/Oracle, you can change the association for jdbc/PriceDB to make it use the Oracle data source. Once again, you don't change the Pricing bean, just its deployment properties.

Assuming you're running the J2EE SDK deploy tool, you set up the jdbc/PriceDB naming entry in the Resource References section of the deploy tool, as shown here in Figure 6.8.

Figure 6.8. The Resource References dialog box lets you configure a session bean's naming context.

The only other difference between the deployment of the Pricing bean and the HelloWorldSession bean is that you must specify the alias for the jdbc/PriceDB in the JNDI Names tab panel, as shown in Figure 6.9.

Figure 6.9. The JNDI names panel lets you set up JNDI aliases for various names your bean uses.

Writing a client to test the Pricing bean is simple and the program looks similar to the other client programs you have seen. Listing 6.12 shows the pricing test client.

Listing 6.12 Source Code for TestPricing.java

package usingj2ee.pricing;

import java.util.*;
import javax.naming.*;
import javax.rmi.*;

public class TestPricing
{
    public static void main(String[] args)
    {
        try
        {

/** Creates a JNDI naming context for location objects */
            Context context = new InitialContext();

/** Asks the context to locate an object named "Pricing" and expects the
    object to implement the PricingHome interface */

            PricingHome home = (PricingHome)
                PortableRemoteObject.narrow(
                    context.lookup("Pricing"),
                    PricingHome.class);
/** Asks the Home interface to create a new session bean */
            Pricing session = (Pricing) home.create();

/** Get a list of valid product codes */
            String[] codes = session.getProductCodes();     

            for (int i=0; i < codes.length; i++)
            {
                System.out.println(codes[i]+":  "+
                    session.getPrice(codes[i]));
            }

            try
            {
                session.getPrice("f00b4r");
            }
            catch (InvalidProductCodeException exc)
            {
                System.out.println("Got invalid product code exception: "+
                    exc.toString());
            }

/** Destroy this session */
            session.remove();

        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}     
					

Finally, Figure 6.10 shows the output from the pricing test client. Notice that nowhere in the source code or the output does the client have any idea that the bean is getting its data from a database.

Figure 6.10. The client doesn't know that the session bean gets its data from a database.

Note

The makeprices.sql script included on the CD-ROM contains insert commands to populate the pricing database.

					
INSERT INTO price (product_code, price) VALUES ('A1', 1.59);

Now that you've started with session beans, Chapter 7, "Creating an Entity Bean," introduces you to the other important EJB: the entity bean. Chapter 8 then shows you how transactions fit in to the EJB world.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020