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> ... </entity> ... </enterprise-beans>
The <resource-ref>
tag is used for any resource (e.g., JDBC, JMS, JavaMail) that is
accessed from the ENC. It describes the JNDI name of the resource
(<res-ref-name>
),
the factory type
(<res-type>
),
and whether
authentication is performed explicitly by
the bean or automatically by the container
(<res-auth>
).
In this example, we are declaring that the JNDI name
jdbc/titanDB
refers to a
javax.sql.DataSource
resource manager and that
authentication to the database is handled automatically by the
container. The JNDI name specified in the
<res-ref-name>
tag is always relative to the
standard JNDI ENC context name, java:comp/env
.
When the bean is deployed, the deployer maps the information in the
<resource-ref>
tag to a live database. This
is done in a vendor-specific manner, but the end result is the same.
When a database connection is requested using the JNDI name
java:comp/jdbc/titanDB
, a
DataSource
for the Titan database is returned.
Consult your vendor’s documentation for details on how to map
the DataSource
to the database at deployment time.
The
getConnection()
method
provides us with a simple and consistent mechanism for obtaining a
database connection for our ShipBean
class. Now
that we have a mechanism for obtaining a database connection, we can
use it to insert, update, delete, and find Ship EJBs in the database.