O'Reilly logo

Enterprise JavaBeans, Third Edition by Richard Monson-Haefel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Obtaining a Resource Connection

In order for a BMP entity bean to work, it must have access to the database or resource to which it will persist itself. To get access to the database, the bean usually obtains a resource factory from the JNDI ENC. The JNDI ENC is covered in detail in Chapter 12, but an overview here will be helpful since this is the first time it is actually used in this book. The first step in accessing the database is to request a connection from a DataSource , which we obtain from the JNDI environment naming context:

private Connection getConnection() throws SQLException {
    try {
        Context jndiCntx = new InitialContext();
        DataSource ds = (DataSource)jndiCntx.lookup("java:comp/env/jdbc/titanDB");
        return ds.getConnection();
    }
    catch (NamingException ne) {
        throw new EJBException(ne);
    }
}

In EJB, every enterprise bean has access to its JNDI environment naming context (ENC), which is part of the bean-container contract. The bean’s deployment descriptor maps resources such as the JDBC DataSource, JavaMail, and Java Message Service to a context (name) in the ENC. This provides a portable model for accessing these types of resources. Here’s the relevant portion of the deployment descriptor that describes the JDBC resource:

<enterprise-beans> <entity> <ejb-name>ShipEJB</ejb-name> ... <resource-ref> <description>DataSource for the Titan database</description> <res-ref-name>jdbc/titanDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required