Class.forName(JDBC_DRIVER) no longer needed? - java

I've read here on SO that since java 6 you no longer need to register JDBC Driver using:
Class.forName(JDBC_DRIVER);
because DriverManager uses the path located in system property "jdbc.drivers"
to retrieve the correct driver.
But when I do the followng:
System.out.print(System.getProperty("jdbc.drivers"));
null gets printed.
Do you have any clue why my app works correctly ?? ;)

That has nothing to do with that system property. Java6 (and JDBC4) introduced a concept known as "service provider" where implementations of known interface can be detected by the JVM during startup. A driver that is compliant with that will be registered by the DriverManager automatically. That's why Class.forName() is no longer necessary - but only if the driver supports that.
The service registration is initiated if there is a services directory in the driver's jar file inside the META-INF directory. That directory needs to contain a text file with the name of the interface that is implemented in the case of a JDBC driver that is java.sql.Driver containing the implementing class.

From the Javadocs of DriverManager:
As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used by their applications. For example in your ~/.hotjava/properties file you might specify:
jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver
This means that the system property need not be specified (as it says DriverManager will attempt). There is another mechanism through which drivers are automatically loaded, which relies on service loading since Java 6:
The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver.
Almost all JDBC drivers now conform to this requirement. Note that DriverManager does not internally fill the jdbc.drivers property, so it's still null.

Related

driver.connect() vs DriverManager.getConnection()

The DriverManager.getConnection makes call to driver.connect() internally to get database connection.
Are there any pitfalls of using driver.connect() directly?
java.sql.Driver is an interface, you need an actual implementation (eg org.firebirdsql.jdbc.FBDriver for Firebird) to actually do anything with it. On the other hand, DriverManager is a concrete class that abstracts (hides) driver loading, selection and usage for you.
Normally you should not use a Driver implementation directly. Stick with either using DriverManager, or otherwise use a DataSource implementation (preferably through configuration).
Using DriverManager decouples your code from the actual driver used. That means you do not have a compile time dependency on a specific driver. Changing drivers or even database system (assuming the SQL is compatible or generated compatibly) is then just a manner of adding/replacing a driver jar on the class path and specifying the right JDBC url in the configuration. That is assuming JDBC 4 automatic driver loading, otherwise adding the specific driver name to the config and using Class.forName(<value from config>) is also necessary.
For example, for SQL Server you have the driver from Microsoft or the jTDS driver (+ other third party drivers). Switching between those is - basically - a matter of adding the right driver to the class path and changing the URL in the configuration.
In the past, Microsoft even had a breaking change in their JDBC driver, changing both the class name of the driver and the URL. If you had hard coded a dependency on the Driver implementation, your code would break if you tried to upgrade the driver. If you had just used DriverManager (and had a config option for the URL, and - this was before automatic driver loading - the driver class name for loading), things would just have continued to work after a configuration change.
There are exceptions where you would use a Driver implementation directly (usually through reflection and still not hard coded), but those situations are rare, and unless you have a very good reason (and know what you're doing) then just don't do that.

Class.forName still seems necessary

From the Java documentation
In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName.
Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)
I have a jersey Webservice which connects to SQL Server Express 2016. It has sqljdbc42.jar which is 4.2 driver, in the CLASSPATH
However, if I omit the Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") call, my DriverManager.getConnection throws a SQLException(No suitable driver found for jdbc:sqlserver://localhost:1433; ....")
The getConnection starts succeeding once I add the Class.forName call.
I am on Java 8.
What am I missing?
UPDATE: I just tried a command line program and it works without the forName. However, from my Eclipse IDE where I am running my REST service as a Tomcat 8.0 Server on localhost, it doesn't work.
The drivers are automatically initialized when the class DriverManager is itself initialized thanks to SPI (Service Provider Interface). Which means that internally it will try to find any file META-INF/services/java.sql.Driver available in the context class loader and for each file found, it will create an instance of the class that is defined in the file which in this case is actually the FQN of the JDBC driver, this is how JDBC drivers are automatically initialized starting from JDBC 4.0.
But this can only work, if your driver is available from the context class loader while initializing the class DriverManager. A good way to ensure that is to make your driver available from a Class Loader high enough in the hierarchy. In your case you should put your driver in tomcat/lib. Indeed, this way your driver will be available from the Common CL which should be high enough. More details about the CL hierarchy in Tomcat here.

Why doesn't Tomcat need to instantiate a database driver? [duplicate]

I understand that class loading is useful for load the class at runtime with its class name.
However while using JDBC in our project we know which driver we are going to use and mostly driver manager string is hard coded.
My question is: Why are we loading driver using Class.forName("JDBC_DRIVER") here?
Why can't we go ahead adding the driver in class path? since we know which driver jar we are going to use.
I believe Class.forName(JDBC_DRIVER) will load the Driver into DriverManager. Is it the only reason?
Edit 1:
The DriverManager API doc states that
As part of its(DriverManager) initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property.
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
Then when I use other than oracle driver; do I need to change the driver name string in system property?
First of: with modern JDBC drivers and a current JDK (at least Java 6) the call to Class.forName() is no longer necessary. JDBC driver classes are now located using the service provider mechanism. You should be able to simply remove that call and leave the rest of the code unchanged and it should continue to work.
If you're not using a current JDK (or if you have a JDBC driver that does not have the appropriate files set up to use that mechanism) then the driver needs to be registered with the DriverManager using registerDriver. That method is usually called from the static initializer block of the actual driver class, which gets triggered when the class is first loaded, so issuing the Class.forName() ensures that the driver registers itself (if it wasn't already done).
And no matter if you use Class.forName() or the new service provider mechanism, you will always need the JDBC driver on the classpath (or available via some ClassLoader at runtime, at least).
tl;dr: yes, the only use of that Class.forName() call is to ensure the driver is registered. If you use a current JDK and current JDBC drivers, then this call should no longer be necesary.
The Class.forName(JDBC_DRIVER) call will register your JDBC driver in the DriverManager, so you can address it by url, such as "jdbc:odbc:Database" and so on...
Usually the driver class has static initialization code like this, which is invoked on Class.forName():
public class Driver implements java.sql.Driver {
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
}
You still have to put JDBC driver jar into the classpath.
As an alternative, you can use database specific DataSource, then you can declaratively specify the datasource type, for example in Spring context or in your Web server JNDI. Here is an example.
Putting a class in the classpath is not sufficient to have it loaded by the class loader. And the driver class must be loaded to ensure that it's registered to the JDBC API. BTW, for Class.forName to work, the driver class must be in the classpath.
In many industrial applications, we would like to abstract the data access layer from the rest of code, by pulling such information in a form of a property file/configuration file. In those cases, we might need to use something as you have done.
For e.g. we can use the JDBC interface classes to write the code to access the database, where you could configure the properties by selecting which technology you want to use as a database (e.g. ojdbc driver, or mysql jdbc driver, etc.) In those cases you can load the class using such method.

What is the purpose of 'Class.forName("MY_JDBC_DRIVER")'?

I understand that class loading is useful for load the class at runtime with its class name.
However while using JDBC in our project we know which driver we are going to use and mostly driver manager string is hard coded.
My question is: Why are we loading driver using Class.forName("JDBC_DRIVER") here?
Why can't we go ahead adding the driver in class path? since we know which driver jar we are going to use.
I believe Class.forName(JDBC_DRIVER) will load the Driver into DriverManager. Is it the only reason?
Edit 1:
The DriverManager API doc states that
As part of its(DriverManager) initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property.
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
Then when I use other than oracle driver; do I need to change the driver name string in system property?
First of: with modern JDBC drivers and a current JDK (at least Java 6) the call to Class.forName() is no longer necessary. JDBC driver classes are now located using the service provider mechanism. You should be able to simply remove that call and leave the rest of the code unchanged and it should continue to work.
If you're not using a current JDK (or if you have a JDBC driver that does not have the appropriate files set up to use that mechanism) then the driver needs to be registered with the DriverManager using registerDriver. That method is usually called from the static initializer block of the actual driver class, which gets triggered when the class is first loaded, so issuing the Class.forName() ensures that the driver registers itself (if it wasn't already done).
And no matter if you use Class.forName() or the new service provider mechanism, you will always need the JDBC driver on the classpath (or available via some ClassLoader at runtime, at least).
tl;dr: yes, the only use of that Class.forName() call is to ensure the driver is registered. If you use a current JDK and current JDBC drivers, then this call should no longer be necesary.
The Class.forName(JDBC_DRIVER) call will register your JDBC driver in the DriverManager, so you can address it by url, such as "jdbc:odbc:Database" and so on...
Usually the driver class has static initialization code like this, which is invoked on Class.forName():
public class Driver implements java.sql.Driver {
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
}
You still have to put JDBC driver jar into the classpath.
As an alternative, you can use database specific DataSource, then you can declaratively specify the datasource type, for example in Spring context or in your Web server JNDI. Here is an example.
Putting a class in the classpath is not sufficient to have it loaded by the class loader. And the driver class must be loaded to ensure that it's registered to the JDBC API. BTW, for Class.forName to work, the driver class must be in the classpath.
In many industrial applications, we would like to abstract the data access layer from the rest of code, by pulling such information in a form of a property file/configuration file. In those cases, we might need to use something as you have done.
For e.g. we can use the JDBC interface classes to write the code to access the database, where you could configure the properties by selecting which technology you want to use as a database (e.g. ojdbc driver, or mysql jdbc driver, etc.) In those cases you can load the class using such method.

JDBC Class.forName vs DriverManager.registerDriver

Which is the difference from forName method vs registerDriver to load and register a JDBC driver?
Class.forName() is not directly related to JDBC at all. It simply loads a class.
Most JDBC Driver classes register themselves in their static initializers by calling registerDriver().
registerDriver() is the real call that you hardly ever need to call yourself (unless you write your own JDBC driver).
Note that in JDBC 4 you should not need either of those if your JDBC driver is up-to-date, as drivers can be found using the service location mechanisms instead (i.e. simply leave out that call and open your connection as usual). See the documentaton of DriverManager for details:
The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver. For example, to load the my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain the entry:
my.sql.Driver
Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
Never call DriverManager.registerDriver() method manually. The JDBC spec requires a driver to register itself when the class is loaded, and the class is loaded via Class.forName(). In JDBC 4 the drivers are able to be loaded automatically just by being on the class path.
DriverManager.registerDriver() manually is potentially dangerous since it actually causes the Driver to be registered twice. If your code requires you to deregister a Driver to prevent a memory leak then you would only end up deregistering it once and leave a second instance registered.
In additaion to what Joachim Sauer already mentioned about JDBC 4 drivers, note that in practice you usually want to inject either an EntityManager (JPA) or a pooled DataSource (and use JdbcTemplate of Spring).

Categories