Tomcat – Configure Database Properties for Tomcat Webapp

javaspringframeworktomcatweb-applications

I setup a sample application in Tomcat but have trouble getting the database connection working. It is a standard WAR package written in Spring framework and uses a MySQL database.

The application is the Granny Address Book from http://www.cumulogic.com/downloads/sample-applications/.

I have deployed it under tomcat/webapps/ (Tomcat 7.0.42 with MySQL 5.1.73 running on the same host.)

  • Mysql DB name: grannydb
  • JNDI Name: MySqlGBDS

I cannot locate where to place the database connection settings, as it does not have the usual database.properties file. The only reference to database settings are in granny.xml:

<database>
  <engine>MySQL-5.5.27</engine>
  <no-of-nodes>1</no-of-nodes>
  <storage>10</storage>
  <config>
    <master-username>demo</master-username>
    <master-password>demodemo</master-password>
    <port>3306</port>
    <character-set>UTF-8</character-set>
  </config>       <external-host></external-host>
</database>

But this file is not packaged inside the webapp (it comes separately,) and it's lacking a database host name.

I tried placing granny.xml inside the webapp, under WEB-INF/classes/META-INF/spring/ but it fails to connect to the database.

The current behavior is the webapp is starting but catalina.out warns:

 WARN : org.hibernate.cfg.SettingsFactory - Could not obtain connection
 to query metadata org.apache.tomcat.dbcp.dbcp.SQLNestedException:
 Cannot create JDBC driver of class '' for connect URL 'null'

Where should granny.xml be placed?
What else is missing?

(Yes I did already create the database and user in MySQL. No tables are getting created by the app.)

Best Answer

If it uses JNDI you need to set up the database connection in either server.xml or context.xml.

As an administrator it is better to setup the database connection in server.xml, otherwise you end up unpacking and packing the WAR-file before each deployment.

Open server.xml. There should be a section called GlobalNamingResources. Here you add your database connection.

<Resource auth="Container" 
          driverClassName="com.mysql.jdbc.Driver" 
          factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
          jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"  
          validationQuery="/* ping */"
          testOnBorrow="true"
          name="jdbc/MySqlGBDS" 
          username="<username>"
          password="<password>" 
          type="javax.sql.DataSource" 
          url="jdbc:mysql://<ipaddress>/grannydb" /> 

Hope this helps.