Connecting to a database via JDBC is essential in many applications. For instance, a session bean needs to access data to complete a business function, and entity beans with bean-managed persistence require access to a JDBC connection to load and store data. The application server running the EJB application provides data sources as specified by the deployer. To retrieve the javax.sql.DataSource object from the application server, we have to complete two steps. First, we have to configure the deployment descriptor for the bean that will need access to the DataSource object. Second, acquire the DataSource reference by performing a JNDI lookup.

////////////// configuration in deployment descriptor:
      <!-- main bean definitions -->
      <!-- definition of resources bean referes -->


////////////// EJB code retreiving data source connection:

import javax.ejb.SessionBean;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection ;

public class TestDBSourceBean implements SessionBean {
  public Connection getConnection() {
    try {
      // prepare context:
      InitialContext context = new InitialContext();
      // retreive DB-source
      DataSource source = (javax.sql.DataSource

      return source.getConnection();
    catch (Exception e) {
    return null;