Class.forName still seems necessary - java

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.

Related

Is Driver registering by `Class.forName()` needed in mysql-connector 8.0?

I already know from on JDBC 4.0. and JDK 6, drivers those are found in classpath are automatically loaded. This is the reason we are used to ignoring that Class.forName(dbDriver); line of code when creating JDBC connection.
But recently I installed MySQL Server 8.0.11 and I updated the driver to mysql-connector-java:8.0.11 in my simple Servlet project that runs on tomcat 8.5.30. But it gives me the infamous exception
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/mysql at ...
But all my code was working and fine before. So then I added the Class.forName("com.mysql.jdbc.Driver");
And it works. I think I didn't miss anything. Can anyone explain to me what it might be the reason?
The JDBC 4.0 (and higher) automatic driver loading works only if the driver jar is on the initial (system) class path of the application. If you are using Tomcat, the driver would have to be in the <catalina-home>/lib folder.
If you deploy the driver together with your application, then the driver is on the context classpath of that specific application, and it will need to be explicitly loaded using Class.forName.
But in practice, you should not be using DriverManager.getConnection to create connections in a web application. You should be using a data source (preferably with connection pooling), either created and initialized in code, or in the context or server configuration of Tomcat. In that case this problem wouldn't even surface, because either the data source already knows how to get the driver, or you have to explicitly configure it with the driver to use anyway.

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.

Class.forName(JDBC_DRIVER) no longer needed?

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.

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