Connecting to JNDI Data Sources

Connecting to an application server’s JNDI data sources from Liferay DXP’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 DXP’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


try {

        // Look up the data source and connect to it

        InitialContext ctx = new InitialContext();
        DataSource datasource = (DataSource)

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

        // Execute SQL statements here ...

catch (NamingException ne) {

catch (SQLException sqle) {

finally {
       // Switch back to the original context class loader


The example code sets Liferay DXP’s classloader on the thread to access the JNDI API.


It uses JNDI to look up the data source.

InitialContext ctx = new InitialContext();
DataSource datasource = (DataSource)

After working with the data source, the code reinstates the thread’s original classloader.


Here are the class imports for the example code:

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.

« Calling Non-OSGi Code that Uses OSGi ServicesDetecting Unresolved OSGi Components »
¿Fue útil este artículo?
Usuarios a los que les pareció útil: 0 de 1