Monday, January 19, 2009

4.1.7 Advantages of Using JNDI

There are major advantages to connecting to a data source using a DataSource object registered with a JNDI naming service rather than using the DriverManager facility. The first is that it makes code more portable. With the DriverManager, the name of a JDBC driver class, which usually identifies a particular driver vendor, is included in application code. This makes the application specific to that vendor's driver product and thus non-portable.

Another advantage is that it makes code much easier to maintain. If any of the necessary information about the data source changes, only the relevant DataSource properties need to be modified, not every application that connects to that data source. For example, if a database is moved to a different server and uses a different port number, only the DataSource object's serverName and portNumber properties need to be updated. A system administrator could keep all existing code usable with the following code fragment. In practice, a system administrator would probably use a GUI tool to set the properties, so the following code fragment illustrates the code a tool might execute internally.

Context ctx = new InitialContext()
DataSource ds = (DataSource)ctx.lookup("jdbc/AcmeDB");
ds.setServerName("my_new_database_server");
ds.setPortNumber("940");

The application programmer would not need to do anything at all to keep all of the applications using the data source running smoothly.

Yet another advantage is that applications using a DataSource object to get a connection will automatically benefit from connection pooling if the DataSource class has been implemented to support connection pooling. Likewise, an application will automatically be able to use distributed transactions if the DataSource class has been implemented to support them.

0 Comments: