Monday, January 19, 2009

4.1.3 Creating and Registering a DataSource Object

A DataSource object is usually created, deployed, and managed separately from the Java applications that use it. For example, the following code fragment creates a DataSource object, sets its properties, and registers it with a JNDI naming service. Note that a DataSource object for a particular data source is created and deployed by a developer or system administrator, not the user.

The class VendorDataSource would most likely be supplied by a driver vendor. (The code example in the next section will show the code that a user would write to get a connection.) Note also that a GUI tool will probably be used to deploy a DataSource object, so the following code, shown here mainly for illustration, is what such a tool would execute.

VendorDataSource vds = new VendorDataSource();
vds.setServerName("my_database_server");
vds.setDatabaseName("my_database");
vds.setDescription("the data source for inventory and personnel");
Context ctx = new InitialContext();
ctx.bind("jdbc/AcmeDB", vds);
The first four lines represent API from a vendor's class VendorDataSource, an implementation of the javax.sql.DataSource interface. They create a DataSource object, vds, and set its serverName, databaseName, and description properties. The fifth and sixth lines use JNDI API to register vds with a JNDI naming service. The fifth line calls the default InitialContext constructor to create a Java object that references the initial JNDI naming context. System properties, which are not shown here, tell JNDI which naming service provider to use. The last line associates vds with a logical name for the data source that vds represents.
The JNDI namespace consists of an initial naming context and any number of subcontexts under it. It is hierarchical, similar to the directory/file structure in many file systems, with the initial context being analogous to the root of a file system and subcontexts being analogous to subdirectories. The root of the JNDI hierarchy is the initial context, here represented by the variable ctx. Under the initial context there may be many subcontexts, one of which is jdbc, the JNDI subcontext reserved for JDBC data sources. (The logical data source name may be in the subcontext jdbc or in a subcontext under jdbc.) The last element in the hierarchy is the object being registered, analogous to a file, which in this case is a logical name for a data source. The result of the preceding six lines of code is that the VendorDataSource object vds is associated with jdbc/AcmeDB. The following section shows how an application uses this to connect to a data source.

0 Comments: