Spring MVC JdbcTemplate with JNDI Datasource in Tomcat Server - Java @ Desk

Saturday, May 7, 2016

Spring MVC JdbcTemplate with JNDI Datasource in Tomcat Server

Spring MVC JdbcTemplate with JNDI Datasource in Tomcat Server

Configuring a datasource through JNDI mapping in Tomcat is beneficial since the database configuration remains independent of application. Configuring a JNDI in Tomcat and using the reference within Spring application to create a JdbcTemplate object achieves the object of loose coupling.

Any database configuration changes would be done at the Tomcat end without affecting the application deployed.

Below are the steps to define a JNDI in Tomcat and use in Spring configuration XML file to map with JdbcTemplate:

1) Create a JNDI configuration in Tomcat:
Open context.xml file in /conf folder and add a Resource entry

<Resource name="jdbc/MyDataSource"
              auth="Container"
              type="javax.sql.DataSource"
              username="${db.user}"
              password="${db.password}"
              driverClassName="${db.driver}"
              url="${db.url}"              
              maxActive="15"
              maxIdle="5"/>


2) Create properties in catalina.properties in /conf folder
db.driver=oracle.jdbc.driver.OracleDriver
db.user=DEVUser
db.password=XPL7TR360
db.url=URL_OF_DB


3) Update Spring configuration xml file to create JNDI mapping
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <constructor-arg ref="dataSource"/>
</bean>
 
<jee:jndi-lookup id="dataSource" expected-type="javax.sql.DataSource" jndi-name="jdbc/MyDataSource" resource-ref="true"/>


4) Inject or Autowire the JdbcTemplate object in classes to perform DB operation






No comments:

Post a Comment