Liferay JNDI Datasource Configuration

How to configure a JNDI DataSource in Liferay/Tomcat


Overview

This article explains how to configure a JNDI DataSource and use it in Liferay 7 bundled with Tomcat.


Configuration


1. Declare a JNDI Resource in tomcat/conf/server.xml, sample:


<Server port="8005" shutdown="SHUTDOWN">

 //...

 <GlobalNamingResources>

   <Resource

           name="jdbc/myDataSource"

           auth="Container"

           type="javax.sql.DataSource"

           factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"

           driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"

           url="jdbc:sqlserver://my-db-url:1433;database=myDB"

           username="test"

           password="test"

           maxActive="20"

           maxIdle="5"

           maxWait="10000"

   />

 </GlobalNamingResources>

 //...

</Server>


Define the resource name and set the DB connection properties as you need.


See also: https://tomcat.apache.org/tomcat-9.0-doc/jndi-resources-howto.html


2. Declare a ResourceLink in tomcat/conf/context.xml, sample:


<Context>

   <WatchedResource>WEB-INF/web.xml</WatchedResource>

   <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>

   <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

   <ResourceLink name="jdbc/myDataSource" global="jdbc/myDataSource" type="javax.sql.DataSource"/>

</Context>


3. Make sure, JDBC Driver for your database is supported by Liferay.


If the driver is not in Liferay OOTB - you can add it by copying the JAR file into tomcat/lib/ext directory. Sample for MS SQL database:


4. Use the JNDI DataSource in your code.


Get the Data Source:


@Activate

public void init() {

   try {

       InitialContext ctx = new InitialContext();

       ds = (DataSource) ctx.lookup(JNDI_DATASOURCE_NAME);

   } catch (Exception e) {

       _log.error("Failed to initialize DataSource, cause: " + e.getMessage());

   }

}


Get Connection from DataSource, and perform the required DB operations:


try (Connection connection = ds.getConnection();) {

    //...

}



Enjoy 😏


Comments

Popular posts from this blog

Liferay Search Container Example

Liferay DXP - max upload file size

Liferay Keycloak integration