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. 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.

Connecting Service Builder to External Data Sources

« Identifying Liferay Artifact Versions for DependenciesAdjusting Module Logging »
Was this article helpful?
2 out of 2 found this helpful