Skip to Main Content
Enterprise JavaBeans, Fourth Edition
book

Enterprise JavaBeans, Fourth Edition

by Sacha Labourey, Bill Burke, Richard Monson-Haefel
June 2004
Intermediate to advanced content levelIntermediate to advanced
792 pages
23h 17m
English
O'Reilly Media, Inc.
Content preview from Enterprise JavaBeans, Fourth Edition

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 11, but an overview here will be helpful since this is one of the first times 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, J2EE Connector, 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> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Enterprise JavaBeans, Third Edition

Enterprise JavaBeans, Third Edition

Richard Monson-Haefel
Enterprise JavaBeans 3.1, 6th Edition

Enterprise JavaBeans 3.1, 6th Edition

Andrew Lee Rubinger, Bill Burke
Enterprise JavaBeans 3.0, 5th Edition

Enterprise JavaBeans 3.0, 5th Edition

Richard Monson-Haefel, Bill Burke

Publisher Resources

ISBN: 059600530XSupplemental ContentCatalog PageErrata