Monday, 15 December 2008

Associate an IDE DB Connection to a Workspace for Web projects in JDeveloper 11g

In JDeveloper 10g you could easily deploy all database connections when running a web project in the embedded OC4J server thus allowing each connection to be represented as a data source at runtime. Turns out the same can be done in JDeveloper 11g and Weblogic Integrated server however the steps are a little different.

1. View -> Database Navigator
2. Drag the IDE connection you wish to use in your workspace. The end result is as follows for the Workspace "WebLogicStuff"





3. Now whenever you run any web project from WebLogicStuff workspace then the database connection "scott" will automatically be deployed as an application level data source.

4. In order to access the connection "scott" we should use a JNDI location as follows within our code.

java:comp/env/jdbc/scottDS

The format would be as follows, depending on the connection name.

java:comp/env/jdbc/{jdevide-connection-name}DS

Here is some java code we can then use to perform a JNDI lookup of the data source via a simple method which requires the location above to be passed to the method.

private Connection getConnection (String dataSourceLocation)
throws NamingException, SQLException
{
Connection conn = null;

// Get a context for the JNDI look up
Context ctx = new InitialContext();

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

// Create a connection object
conn = ds.getConnection();

return conn;
}

No comments: