Java Reference
In-Depth Information
manually deploy a DataSource object by using code that will look like the follow-
ing:
org.java8recipes.chapter13.recipe13_01.FakeDataSourceDriver
ds =
new
org.java8recipes.chapter13.recipe13_1.FakeDataSourceDriver();
ds.setServerName("my-server");
ds.setDatabaseName("JavaRecipes");
ds.setDescription("Database connection for Java
8 Recipes");
This code instantiates a new DataSource driver class and then sets properties
based on the database that you want to register. DataSource code such as that
demonstrated here is typically used when registering a DataSource in an application
server or with access to a JNDI server. Application servers usually do this work behind
the scenes if you are using a web-based administration tool to deploy a DataSource .
Most database vendors will supply a DataSource driver along with their JDBC
drivers, so if the correct JAR resides within the application or server CLASSPATH , it
should be recognized and available for use. Once a DataSource has been instanti-
ated and configured, the next step is to register the DataSource with a JNDI naming
service.
The following code demonstrates the registration of a DataSource with JNDI:
try {
Context ctx = new InitialContext();
DataSource ds =
(DataSource) ctx.bind("jdbc/java8recipesDB");
} catch (NamingException ex) {
ex.printStackTrace();
}
Once the DataSource has been deployed, any application that has been deployed
to the same application server will have access to it. The beauty of working with a
DataSource object is that your application code doesn't need to know anything
about the database; it only needs to know the name of the DataSource . Usually the
name of the DataSource begins with a jdbc/ prefix, followed by an identifier. To
look up the DataSource object, an InitialContext is used. The Ini-
Search WWH ::




Custom Search