Connecting to JNDI Data Sources

Connecting to an application server’s JNDI data sources from Liferay Portal’s OSGi environment is almost the same as connecting to them from the Java EE environment. In an OSGi environment, the only difference is that you must use Liferay Portal’s class loader to load the application server’s JNDI classes. The following code demonstrates this.

Thread thread = Thread.currentThread();

// Get the thread's class loader. You'll reinstate it after using
// the data source you look up using JNDI

ClassLoader origLoader = thread.getContextClassLoader();

// Set Liferay's class loader on the thread

thread.setContextClassLoader(PortalClassLoaderUtil.getClassLoader());

try {

        // Look up the data source and connect to it

        InitialContext ctx = new InitialContext();
        DataSource datasource = (DataSource)
            ctx.lookup("java:comp/env/jdbc/TestDB");

        Connection connection = datasource.getConnection();
        Statement statement = connection.createStatement();

        // Execute SQL statements here ...

        connection.close();
}
catch (NamingException ne) {

    ne.printStackTrace();
}
catch (SQLException sqle) {

    sqle.printStackTrace();
}
finally {
       // Switch back to the original context class loader

       thread.setContextClassLoader(origLoader);
}

The example code sets Liferay Portal’s classloader on the thread to access the JNDI API. After working with the data source, the code reinstates the thread’s original classloader.

Here are the class imports for the code above:

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;

Your applications can use similar code to access a data source. Make sure to substitute jdbc/TestDB with your data source name.

An easier way to work with databases is to connect to them using Service Builder.

Related Topics

Connecting Service Builder to External Data Sources

0 (0 Votes)
Identifying Liferay Artifact Versions for Dependencies Previous