This Blog will help us to learn about the JNDI Data Source Configuration in Liferay DXP. We have tested this with Liferay 7.3 with Tomcat.
1. Make Sure JDBC Driver for your data base is available in your Liferay Tomcat Server 😀 without that nothing will work.
2. Declare a JNDI Resource in tomcat/conf/server.xml : Below is sample of the Resource tag and parameters you can customize as per your requirements
<Server port="8005" shutdown="SHUTDOWN">
<GlobalNamingResources>
<Resource
name="jdbc/CustomDataSource"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://url:1433;database=mySchema"
username="mysql"
password="mysql"
maxActive="20"
maxIdle="5"
maxWait="19999"
/>
</GlobalNamingResources>
</Server>
3. Declare a ResourceLink in tomcat/conf/context.xml : Below is sample of the Context tag and content.
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<ResourceLink name="jdbc/CustomDataSource" global="jdbc/CustomDataSource" type="javax.sql.DataSource"/>
</Context>
4. Using JNDI Custom Data Source in your Code.
- First we need to load the Data Source from the Context, below code will be hepful to load data Source.
public void init() {
try {
//API to load the Context
InitialContext ctx = new InitialContext();
// Below code will use to get the Data Source from Context
ds = (DataSource) ctx.lookup(JNDI_DATASOURCE_NAME);
} catch (Exception e) {
_log.error("Failed to initialize DataSource, cause: " + e.getMessage());
}
}
- Once we have Data Source then we can get the connections.
Connection connection = ds.getConnection();
}
Hope this Blog is helpfull !