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> ...
Get Enterprise JavaBeans, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.