Welcome!

Java IoT Authors: Liz McMillan, Pat Romanski, Yeshim Deniz, Roger Strukhoff, Elizabeth White

Related Topics: Java IoT

Java IoT: Article

The Evolution Of Connecting

The Evolution Of Connecting

So here you are, the eager Java developer, about to embrace JDBC (Java Database Connectivity), the next item on your Java technology checklist. If you followed my last article (JDJ, Vol. 5, issue 9), you've selected a database system and a JDBC driver to help you master this technology. Now you want to jump in and start writing code. Perhaps you've bought a JDBC book, read your JDBC driver documentation or collected various JDBC articles from magazines (such as this one). Unfortunately, many of these resources skim the introductory topics or, worse, offer seemingly conflicting code examples. This article discusses the details of connecting a Java application to a database using JDBC, including how the process has changed with the evolution of the Java programming language.

In theory, the basics of connecting a running Java application to a database are quite simple. Fundamentally, an application developer merely has to code to the JDBC API (see http://java.sun.com/j2se/1.3/docs/api/java/sql/package-summary.html for specific information on the J2SE 1.3 JDBC API). This API has seven classes. Only one, the DriverManager class, is commonly used by beginners. The bulk of the API is dominated by interfaces that must be implemented by the JDBC driver vendors. As previously discussed, this allows for a wide range in performance and flexibility due to specific implementation details. As is often the case, however, the devil is in the details, and there are a lot of details whenever databases are involved.

Before delving into them, however, a mental picture (see Figure 1 for an actual picture) of the process involved in connecting to a database can be useful in understanding why things behave the way they do. First, while seemingly obvious, the fundamental point to start with is that all Java code runs inside a specific Java Virtual Machine (JVM). Meanwhile, the database system of interest has its own interfaces and protocols, which are generally controlled by a server or daemon process. In order for these two server processes to communicate, a bridge must be established and that's accomplished via the JDBC driver. In this article we'll use a fictitious JDBC driver, aptly from the Acme Corporation, whose fully resolved class name is com.acme.jdbc.AcmeDriver. While database servers are in general explicitly designed to allow interprocess communication, the JVM, for obvious security reasons, is not. Therefore, the driver of another Java application also runs inside the same JVM as the Java database application and must provide this extra functionality.

Finding a Driver
Before it can be used, the JVM must "know" about the JDBC driver, which consists of two separate steps: loading and instantiation. The Java object that manages all of the JDBC drivers for a JVM is the DriverManager class. This single class is responsible for shouldering the burden of managing the pool of JDBC drivers that are available within a given JVM. The loading step can be done in two different fashions: static or dynamic loading. The first technique, which is rarely discussed in the popular literature, is static loading during the JVM initialization. This is accomplished by specifying the fully resolved driver (or drivers if multiple JDBC drivers are required) class to the JVM via the jdbc.drivers property:

java –Djdbc.drivers=com.acme.jdbc.AcmeDriver Test.java
One of the benefits of this approach is that the code doesn't need to be tied explicitly to a particular JDBC driver, allowing for changes in the actual driver used to be made by the system administrator (who ostensibly would be starting the JVM as a server process) without recompiling (and redistributing class files). Multiple-driver classes can be loaded in this fashion by separating them with colons, which could be important if the Java applications running inside the same JVM need to communicate to different databases.

The alternative approach is to dynamically load the JDBC driver within the actual Java application, which is done using the Java Reflection mechanism:

Class.forName(com.acme.jdbc.AcmeDriver) ;
This approach allows an application to dynamically load the requested driver (which can be specified at runtime). Of course, this requires that the driver class is actually in the CLASSPATH of the running JVM. This last point is one of the leading stumbling blocks for JDBC novices, as they will receive a ClassNotFoundException if the JVM can't find the requested class. If multiple drivers are loaded, any drivers listed in the jdbc.drivers property are registered first, followed by any dynamically loaded drivers.

Once a JDBC driver has been loaded into the JVM, it must be instantiated. The recommended method of designing drivers is to force them to be automatically instantiated during the loading process: that means that an application developer is able to load and instantiate the JDBC driver in one line of code. This is accomplished via a static initializer that creates a new instance of the driver class and registers the new driver object with the JDBC DriverManager object. As a result, the single line of code above is translated into the following steps:

  1. JVM locates the requested driver class, which must be in the current CLASSPATH.
  2. The JVM loads the driver class into memory.
  3. The JVM executes the static initializer section of the driver class, which will create a new instance of the driver class and register this new instance with the DriverManager class.
This whole process should seem rather straightforward, so what cause is there for any concern? As a popular Java colloquialism states, "Write once, debug everywhere." The problem is that your Java code will need to run in a multitude of JVM implementations, all of which can have subtle variations. For example, some Microsoft virtual machines include a performance trick that loads Java classes differently than many other virtual machines. Unfortunately, this trick prevents the static initializer section from being executed until the JVM feels the class is actually needed. As a result, the driver is neither instantiated nor registered with the DriverManager object during the reflection process. To circumvent this "feature," the developer is required to perform these steps manually:
Class.forName(com.acme.jdbc.AcmeDriver).newInstance() ;

This is not only a "Microsoft problem," as even the Sun JDK 1.1 reference implementation does not work properly due to a race condition (see the JDBC FAQ for more information) that prevented the static initializer section from being processed. The workaround for this bug is for the user to explicitly create and register the driver class:

java.sql.DriverManager.registerDriver(new com.acme.jdbc.AcmeDriver()) ;
Fortunately, with the maturation of both Java and the JDBC driver implementations, these subtle variations are becoming less common (particularly if JDBC is confined to the server). This implies that the following code snippet is all that is required to explicitly instantiate and register a JDBC driver: try {
Class.forName("com.acme.jdbc.AcmeDriver") ;
}catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ") ;
System.err.println(e.getMessage()) ;
}
Making the Connection
Once the driver class has been initialized, a Java application can request a connection from the DriverManager class. The DriverManager object selects the appropriate JDBC driver from its pool of registered drivers based on the specific JDBC URL passed to the DriverManager getConnection method. The DriverManager object tests each registered driver, using the provided URLs in the order in which they were registered. The first one that recognizes (i.e., establishes a connection) the JDBC URL is used to provide the actual database connection. Interestingly enough, this process is actually layered on top of the original antiquated method for establishing a database connection, which is occasionally still prominently mentioned in the documentation of certain JDBC drivers.
Driver driver = new com.acme.JdbcDriver() ;
Connection con = driver.connect(url) ;
A JDBC URL follows the standard URL syntax (i.e., Web addresses), which includes the database name, the database server and optional additional parameters such as username and password. Instead of the more familiar protocols such as HTTP or FTP, the jdbc protocol is used. This is followed by a subprotocol which is designated by the individual driver vendors and registered with Sun to prevent confusing duplications. The last part of the URL is a subname that provides a mapping to the actual database of interest. The subname section of a URL can vary significantly from vendor to vendor; for example, the following are all valid JDBC URLs:
// An ODBC registered data source
String url = "jdbc:odbc:DataSourceName" ;

// An Oracle 8i database with thin client connection
String url = "jdbc:oracle:thin:@server.acme.com:1521:jdbc" ;
// A Microsoft SQL Server database
String url = "jdbc:JTurbo://server.acme.com:1433/jdbc" ;

// A mSQL database
String url = "jdbc:msql://localhost:1114/jdbc" ;

Once the URL is known, obtaining the connection object is straightforward:
try {
Connection con = DriverManager.getConnection(url);
// Utilize the connection to make a query
con.close();
}catch(SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}

Of course, the getConnection method has two additional signatures that allow the developer to pass additional information, such as a username and password, to the database.

The Evolution to Data Sources
While it might seem rather odd at first glance, the JDBC 2.0 specification introduced a new technique for establishing connections to a database, the DataSource object. In fact, the DriverManager class may be deprecated in future versions of Java. The main reason for this abrupt change is the emergence of server-side Java applications within the Enterprise framework. While a DriverManager object is limited in the functionality it can provide (i.e., it essentially serves as a JDBC driver pool), a DataSource object can represent an arbitrary data source, work with JNDI (Java Naming and Directory Interface), provide connection pooling (simplifies tracking license and database cursor limitations) and provide support for distributed transactions (which is important for Enterprise JavaBeans). Each of these new features provides powerful new functionality that exceeds the scope of this article.

While the future of Java Database Connectivity clearly lies with DataSource objects, the traditional DriverManager connection techniques will not disappear. Hopefully this article has helped to illuminate some of the finer points involved in connecting your Java application to a database. Once connected, the rest is SQL.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
SYS-CON Events announced today that Synametrics Technologies will exhibit at SYS-CON's 22nd International Cloud Expo®, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Synametrics Technologies is a privately held company based in Plainsboro, New Jersey that has been providing solutions for the developer community since 1997. Based on the success of its initial product offerings such as WinSQL, Xeams, SynaMan and Syncrify, Synametrics continues to create and hone inn...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
"Digital transformation - what we knew about it in the past has been redefined. Automation is going to play such a huge role in that because the culture, the technology, and the business operations are being shifted now," stated Brian Boeggeman, VP of Alliances & Partnerships at Ayehu, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
Product connectivity goes hand and hand these days with increased use of personal data. New IoT devices are becoming more personalized than ever before. In his session at 22nd Cloud Expo | DXWorld Expo, Nicolas Fierro, CEO of MIMIR Blockchain Solutions, will discuss how in order to protect your data and privacy, IoT applications need to embrace Blockchain technology for a new level of product security never before seen - or needed.
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Digital Transformation (DX) is not a "one-size-fits all" strategy. Each organization needs to develop its own unique, long-term DX plan. It must do so by realizing that we now live in a data-driven age, and that technologies such as Cloud Computing, Big Data, the IoT, Cognitive Computing, and Blockchain are only tools. In her general session at 21st Cloud Expo, Rebecca Wanta explained how the strategy must focus on DX and include a commitment from top management to create great IT jobs, monitor ...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...