October 26, 2015

Obtain a connection to DataSource in Weblogic Server

In other word "How to obtain a remote connection to a DataSource in Weblogic Server"

1. Standard way to obtain a connection from a local server on web appliation

1.1 Define the DataSource name in web.xml file as follow:

<resource-ref>
    <description>Oracle Datasource example</description>
    <res-ref-name>jdbc/testDS</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

1.2 In Java class you lookup for the DataSource as follow:

String dataSourceName = "jdbc/testDS"
Context initialContext = new InitialContext();
DataSource dataSource = (DataSource) initialContext.lookup("java:comp/env/" + dataSourceName);
connection = dataSource.getConnection();

2. Obtain a REMOTE connection from a local server on web application

2.1. No need to define anything on web.xml file

2.2. In Java class you look for the DataSource as follow:

String dataSourceName = "jdbc/testDS"
Context initialContext = new InitialContext();
Properties env = new Properties();
env.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
env.put("java.naming.provider.url", "t3://localhost:7001");
DataSource dataSource = (DataSource) initialContext.lookup(dataSourceName);
connection = dataSource.getConnection();