DataSource - Yash-777/LearnJava GitHub Wiki

Standalone Application stackpost

Here is a simple example of how to create and use a data source.

Web Application:

Tomcat provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java Enterprise Edition application server. The Java EE standard provides a standard set of elements in the /WEB-INF/web.xml file to reference/define resources.

web.xmlweb-app_2_3.dtd configuration « Declare Your Resource Requirements

The following elements may be used in the web application deployment descriptor (/WEB-INF/web.xml) of your web application to define resources:

  • <env-entry> - Environment entry, a single-value parameter that can be used to configure how the application will operate.
  • <resource-ref> - Resource reference, which is typically to an object factory for resources such as a JDBC DataSource, a JavaMail Session, or custom object factories configured into Tomcat.
  • <resource-env-ref> - Resource environment reference, a new variation of resource-ref added in Servlet 2.4 that is simpler to configure for resources that do not require authentication information. Providing that Tomcat is able to identify an appropriate resource factory to use to create the resource and that no further configuration information is required, Tomcat will use the information in /WEB-INF/web.xml to create the resource.

References to Resources

Declaration of a reference to a JDBC connection factory that returns objects of type javax.sql.DataSource:

<resource-ref>
<description> Primary database </description>
<res-ref-name> jdbc/primaryDB </res-ref-name>
<res-type> javax.sql.DataSource </res-type>
<res-auth> Container </res-auth>
</resource-ref>

<res-type> is a fully-qualified class name of the resource factory. The variable can be assigned either Container or Application as a value.

If Container is specified, the web container handles the authentication before binding the resource factory to JNDI lookup registry. If Application is specified, the servlet must handle authentication programmatically. Different resource factories are looked up under a separate sub-context that describes the resource type, follows:

  • jdbc/ for a JDBC javax.sql.DataSource factory
  • mail/ for a JavaMail javax.mail.Session factory
  • url/ for a java.net.URL factory

Naming References and Binding Information JNDI Lookups and Their Associated References

JNDI Lookup Name Associated Reference
java:comp/env Application environment entries
java:comp/env/jdbc JDBC DataSource resource
java:comp/env/mail JavaMail Session Connection Factories
java:comp/env/url URL Connection Factories

context.xml configuration « Configure Tomcat's Resource Factory

If Tomcat is unable to identify the appropriate resource factory and/or additional configuration information is required, additional Tomcat specific configuration must be specified before Tomcat can create the resource. Tomcat specific resource configuration is entered in the elements that can be specified in either $CATALINA_BASE/conf/server.xml or, preferably, the per-web-application context XML file (META-INF/context.xml).

Tomcat JDBC: As a Resource in context.xml.

configuration driverClassName url
MySQL com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/javatest
Oracle 8i, 9i & 10g oracle.jdbc.OracleDriver jdbc:oracle:thin:@127.0.0.1:1521:mysid
PostgreSQL org.postgresql.Driver jdbc:postgresql://127.0.0.1:5432/mydb

Code Your Application's Use Of This Resource

A typical use of this resource environment reference might look like this:

Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/primaryDB");
Connection conn = ds.getConnection();
//etc.

Web application xml configuration.

<!-- context.xml -->
<Context>
    <Environment name="dev" value="jdbc/devdb" type="java.lang.String" override="false" />
    <Environment name="qa" value="jdbc/testdb" type="java.lang.String" override="false" />

    <Resource name="jdbc/devdb" type="javax.sql.DataSource" <!-- ... --> />
    <Resource name="jdbc/testdb" type="javax.sql.DataSource" <!-- ... --> />
</Context>
<!-- web.xml -->
<!-- JDBC DataSources (java:comp/env/jdbc) -->
<resource-ref>
	<description> Development database </description>
	<res-ref-name> jdbc/devdb </res-ref-name>
	<res-type> javax.sql.DataSource </res-type>
	<res-auth> Container </res-auth>
</resource-ref>
<resource-ref>
	<description> Testing database </description>
	<res-ref-name> jdbc/testdb </res-ref-name>
	<res-type> javax.sql.DataSource </res-type>
	<res-auth> Container </res-auth>
</resource-ref>

Initial Naming Context The naming support in Sun Java System Web Server is based primarily on J2SE 1.3, with a few added enhancements.When an application component creates the initial context by using InitialContext(), Sun Java System Web Server returns an object that serves as a handle to the Web application’s naming environment. This object in turn provides sub-contexts for the java:comp/env namespace. Each Web application gets its own namespace java:comp/env name space is allotted to each Web application and objects bound in one Web application’s namespace do not collide with objects bound in other Web applications.

Strng JNDI_Lookup_Name = "java:comp/env/";

String ResourceName1 = "jdbc/devdb", ResourceName2 = "jdbc/testdb";
String env1 = "dev", env2 = "test";

InitialContext initContext = new InitialContext();

// context lookup "java:comp/env/jdbc/devdb"
DataSource ds = initContext.lookup(JNDI_Lookup_Name + ResourceName1);

// context environment lookup
Context envContext  = (Context)initContext.lookup(JNDI_Lookup_Name);
DataSource ds = (DataSource)envContext.lookup(ResourceName1);

// Environment resource name lookup
String env_resourceName = (String)initialContext.lookup(JNDI_Lookup_Name + env1);
DataSource ds = (DataSource)initialContext.lookup(JNDI_Lookup_Name + env_resourceName);

Connection conn = ds.getConnection();

Database URLs are strings. The complete URL syntax is:

jdbc:oracle:driver_type:[username/password]@database_specifier

jdbc:<DB>:<drivertype>:<HOST>:<TCP/IP PORT>:<dataBaseName>
jdbc:oracle:thin:@localhost:1521:myDBName
jdbc:mysql://localhost:3306/myDBName

The first part of the URL specifies which JDBC driver is to be used. The supported driver_type values are thin, oci, and kprb.

  • Oracle Net connection descriptor support thin driver.
String url="jdbc:oracle:thin:@(DESCRIPTION=
	  (LOAD_BALANCE=on)
	(ADDRESS_LIST=
	  (ADDRESS=(PROTOCOL=TCP)(HOST=host1) (PORT=1521))
	 (ADDRESS=(PROTOCOL=TCP)(HOST=host2)(PORT=1521)))
	 (CONNECT_DATA=(SERVICE_NAME=service_name)))"
  • Thin-style service name
"jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename"

SERVICE_NAME: Use the parameter SERVICE_NAME to identify the Oracle9i or Oracle8 database service to access. Set the value to a value specified by the SERVICE_NAMES parameter in the initialization parameter file.

SID: Use the parameter SID to identify the Oracle8 database instance by its Oracle System Identifier (SID). If the database is Oracle9i or Oracle8, use the SERVICE_NAME parameter rather than the SID parameter.

Embed this parameter under the CONNECT_DATA parameter.

Example

net_service_name= 
 (DESCRIPTION=
   (ADDRESS=...)
   (ADDRESS=...)
   (CONNECT_DATA=
    (SID=sales)))


accessToUnderlyingConnectionAllowed

<Resource name="jdbc/dbName" type="javax.sql.DataSource"
    username="scott" password="tiger" 
    url="jdbc:oracle:thin:@(DESCRIPTION=(ENABLE=BROKEN)
        (ADDRESS=(PROTOCOL=tcp)(PORT=1521)(HOST=host))(CONNECT_DATA=(SID=service_id_applets)))"
    driverClassName="oracle.jdbc.driver.OracleDriver" maxTotal="20" maxIdle="10"
    maxWaitMillis="5000" minEvictableIdleTimeMillis="300000"
    timeBetweenEvictionRunsMillis="600000" validationInterval="600000"
    validationQuery="select 1 from dual" testOnBorrow="true" auth="Container"
    accessToUnderlyingConnectionAllowed="true" />

If true the raw physical connection to the database can be accessed using the following construct:

Connection conn = ds.getConnection();
Connection rawConn = ((DelegatingConnection) conn).getInnermostDelegate();
...
conn.close()

Default is false, because misbehaving programs can do harmfull things to the raw connection shuch as closing the raw connection or continuing to use the raw connection after it has been assigned to another logical connection. Be careful and only use when you need direct access to driver specific extensions.

NOTE: Do NOT close the underlying connection, only the original logical connection wrapper.

⚠️ **GitHub.com Fallback** ⚠️