Vitz
Vitz

Reputation: 103

How to put my DB connection outside the .war file?

I have a web application in Java that runs on Apache Tomcat 7 and at some point does the following connection into a database:

    DBConnection database = new DBConnection(
       "user", "password", "jdbc:sqlserver://localhost:1433"
       );

    database.connect();

    Connection conn = database.getConn();

DBConnection is a class I made that has some code about the DB, nothing special (it has the JDBC driver and all). What we can see here is a working connection from Java to a SQLServer DB.

My question is when I generate the .war, if I want to quickly change to another DB...I basically can't! (not without having to change these lines to the respective DB and generate a whole new .war).

I wanted to have a quick way of changing into different DBs, apparently what I need to use is JNDI context with DataSource and create a Resource that will be the DB connection...and then if I want to change a DB just change the parameters of the Resource.

The question is I can't find a working tutorial that fits my problem...and I've been trying for hours. The maximum point I've got was having a NoInitialContextException, but I searched for this error in the web and I can't seem to find a correct explanation.

If someone could shed light into my problem I would be much appreciated.

PS: Sorry for bad English or formatting.

Upvotes: 2

Views: 2690

Answers (2)

Jan Nielsen
Jan Nielsen

Reputation: 11849

Put connection information in a property file, and replace your hard-coded values with references to properties. A better approach is to use a framework for all this, like Spring Data:

http://spring.io/guides/gs/accessing-data-jpa/

This tutorial shows you how to do this in the context.xml file which you can configure Apache Tomcat to reread:

http://www.codejava.net/frameworks/spring/configuring-spring-mvc-jdbctemplate-with-jndi-data-source-in-tomcat

Upvotes: 1

Vishrant
Vishrant

Reputation: 16698

Create a Data Source in your server. Here are the steps.

You will get the connection using below JNDI Look up:

private DataSource getDataSource (String dataSourceLocation) throws NamingException
  {
    // Get a context for the JNDI look up
    Context ctx = new InitialContext();
    Context envContext = (Context) ctx.lookup("java:/comp/env");

    // Look up a data source
    javax.sql.DataSource ds
      = (javax.sql.DataSource) envContext.lookup (dataSourceLocation); 

    return ds;
  }

  private Connection getConnection (DataSource ds) throws SQLException
  {
    Connection conn = null;
    // Get a connection object
    conn = ds.getConnection();

    return conn;
  }

Note: The dataSouceLocation would be "jdbc/UCPPool".

Upvotes: 1

Related Questions