JDBC Deployment Error - NoClassDefFound - java

I've been working with a Java program which performs several queries against an Oracle database. I'm currently using the jdbc thin client (ojdbc7.jar) for this. For an IDE I'm using NetBeans, and debugging or running the JAR on my PC I've faced no Errors. Running this JAR on a Linux environment for production however, the following error is reported:
Exception in thread "main" java.lang.NoClassDefFoundError: oracle/jdbc/OracleDriver
[...]
Caused by: java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver
The code I'm using to get the connection is:
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", DBUsername);
connectionProps.put("password", DBPassword);
conn = DriverManager.getConnection(JDBCConnection, DBUsername, DBPassword);
With DBUsername/Password and JDBCConnection all being locally stored. Adding additional print statements shows the failing line is:
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
I currently have ojdbc7.jar included under Libraries in my project. Checking the project properties under Build > Packaging, "Copy Dependent Libraries" is checked. My expectation at this point is the library should be included in my jar file.
I have also tested:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Similarly, I've tried using only Class.forName(), and using both.
Class.forName("oracle.jdbc.driver.OracleDriver");
Reading other questions, I understand this could be an issue with my classpath. In the Linux environment I'm trying to run this in, I set the classpath to the exact location of the ocjdb7.jar without luck:
export CLASSPATH=/<Directory Location>/ocjdb7.jar
I've tried multiple configurations of this, for example the Linux environment in question already had a classpath including ocjdb6.jar, so I recompiled with this version, set the classpath, and tested. Same error message reported. Have I missed a necessary setup to include this driver? Testing on a coworkers Windows 7 desktop, the same error occurred which seems to indicate this is still a setup issue.

The answer was simple - Netbeans includes any referenced libraries in a lib folder under the dist folder it compiles the JAR files to. I had been copying only the compiled JAR, but not the associated lib folder. After copying the lib folder, the process ran without exceptions.
Netbeans documentation covers how this functions, which states:
https://netbeans.org/kb/articles/javase-deploy.html
If you have specified any libraries for the project (in addition to the JDK), a lib folder is created in the dist folder. The libraries are copied into dist/lib.

The ocjdb7.jar should be packaged into your executable JAR. I suggest you try to make a maven project out of it (NetBeans should have a convenient wizard for that) and reference it as a dependency.
You can also check, if the required ocjdb7.jar was packaged into your JAR when you extract it (a JAR is just an archive file).

Related

Java/Servlet error with calculation class [duplicate]

There is a VERY similar question to mine but in my case I don't have any duplicate jars in my build path, so the solution does not work for me. I've searched google for a couple of hours now, but none of the solutions I've found there actually resolve my issue. I'm creating a web site with some database connectivity for a homework. I'm using a MySQL database, developing in Eclipse and running on Windows.
I keep getting java.lang.ClassNotFoundException: com.mysql.jdbc.Driver with the following code:
import java.sql.*;
//...
public void someMethodInMyServlet(PrintWriter out)
{
Connection connection = null;
PreparedStatement query = null;
try {
out.println("Create the driver instance.<br>");
Class.forName("com.mysql.jdbc.Driver").newInstance();
out.println("Get the connection.<br>");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "secret");
query = connection.prepareStatement( "SELECT * FROM customers");
//...
} catch (Exception e)
{
out.println(e.toString()+"<br>");
}
}
//...
When I run the above code I get the following output:
Create the driver instance.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
It doesn't get past the Class.forName... line and I can't figure out why! Here is what I did:
Download mysql-connector.
Put it in my MySQL folder C:\Program Files\MySQL\mysql-connector-java-5.1.12\mysql-connector-java-5.1.12-bin.jar.
Opened the project properties in Eclipse.
Add External Jar to my Build Path and I selected mysql-connector-java-5.1.12-bin.jar.
Every time I attempt to use the servlet I get the same error regardless if I have the jar in there or if I don't. Could you help me figure this out?
As for every "3rd-party" library in flavor of a JAR file which is to be used by the webapp, just copy/drop the physical JAR file in webapp's /WEB-INF/lib. It will then be available in webapp's default classpath. Also, Eclipse is smart enough to notice that. No need to hassle with buildpath. However, make sure to remove all unnecessary references you added before, else it might collide.
An alternative is to install it in the server itself by dropping the physical JAR file in server's own /lib folder. This is required when you're using server-provided JDBC connection pool data source which in turn needs the MySQL JDBC driver.
See also:
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
How should I connect to JDBC database / datasource in a servlet based application?
Where do I have to place the JDBC driver for Tomcat's connection pool?
JDBC CLASSPATH Not Working
Since you are running it in servlet, you need to have the jar accessible by the servlet container. You either include the connector as part of your application war or put it as part of the servlet container's extended library and datasource management stuff, if it has one. The second part is totally depend on the container that you have.
The others are right about making the driver JAR available to your servlet container. My comment was meant to suggest that you verify from the command line whether the driver itself is intact.
Rather than an empty main(), try something like this, adapted from the included documentation:
public class LoadDriver {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
}
}
On my platform, I'd do this:
$ ls mysql-connector-java-5.1.12-bin.jar
mysql-connector-java-5.1.12-bin.jar
$ javac LoadDriver.java
$ java -cp mysql-connector-java-5.1.12-bin.jar:. LoadDriver
On your platform, you need to use ; as the path separator, as discussed here and here.
Place mysql-connector-java-5.1.6-bin.jar to the \Apache Tomcat 6.0.18\lib folder. Your problem will be solved.
What you should not do do (especially when working on a shared project)
Ok, after had the same issue and after reading some answers here and other places. it seems that putting external lib into WEB-INF/lib is not that good idea as it pollute webapp/JRE libs with server-specific libraries - for more information check this answer"
Another solution that i do NOT recommend is: to copy it into tomcat/lib folder. although this may work, it will be hard to manage dependency for a shared(git for example) project.
Good solution 1
Create vendor folder. put there all your external lib. then, map this folder as dependency to your project. in eclipse you need to
add your folder to the build path
Project Properties -> Java build path
Libraries -> add external lib or any other solution to add your files/folder
add your build path to deployment Assembly (reference)
Project Properties -> Deployment Assembly
Add -> Java Build Path Entries
You should now see the list of libraries on your build path that you can specify for inclusion into your finished WAR.
Select the ones you want and hit Finish.
Good solution 2
Use maven (or any alternative) to manage project dependency
Just follow these steps:
1) Install eclipse
2) Import Apache to eclipse
3) Install mysql
4) Download mysqlconnector/J
5) Unzip the zipped file navigate through it until you get the bin file in it. Then place all files that are present in the folder containing bin to C:\Program Files\mysql\mysql server5.1/
then give the same path as the address while defining the driver in eclipse.
That's all very easy guys.
If the problem still persists,
Put the-
mysql-connector-java-5.0.8-bin jar in a place inside your Tomcat->lib->folder (No matter where you've installed your Tomcat). And change your environmental variable (Done by clicking Properties of Mycomputer -Advanced system settings- Environmental variables-And set a new variable name & variable values as the place where your lib file resides.Dont forget to enter a ; at the end of the path)
If still problem persists
Try downloading commons-collections-2.0.jar (http://www.docjar.com/jar_detail/commons-collections-2.0.jar.html) and paste the jar in the same place where your mysql jar resides (ie) inside Tomcat-lib.
Clean your project-Stop your server- Finally try to run.
Many times I have been facing this problem, I have experienced ClassNotFoundException.
if jar is not at physical location.
So make sure .jar file(mysql connector) in the physical location of WEB-INF lib folder. and
make sure restarting Tomcat by using shutdown command in cmd.
it should work.
The only solution worked for me is putting the .jar file under WEB-INF/lib . Hope this will help.
assuming your project is maven based, add it to your POM:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
Save > Build > and test connection again. It works! Your actual mysql java connector version may vary.
Put mysql-connector-java-5.1.38-bin.jar to the C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib folder.by doing this program with execute
My issue was a little different. Instead of jdbc:oracle:thin:#server:port/service i had it as server:port/service.
Missing was jdbc:oracle:thin:# in url attribute in GlobalNamingResources.Resource. But I overlooked tomcat exception's
java.sql.SQLException: Cannot create JDBC driver of class 'oracle.jdbc.driver.OracleDriver' for connect URL 'server:port/service'
for this error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
you need to:
Import java.sql.*;
Import com.mysql.jdbc.Driver;
even if its not used till app running.

Why am I getting NoClassDefFoundError / ClassNotFoundException

I have been following this tutorial accordingly.
Up to running the FirstExample class in the command prompt is when it starts to freak out for some reason. After attempting to run the following command:
java FirstExample
I get the following exception:
Exception in thread "main" java.lang.NoClassDefFoundError: FirstExample
I understand that it can't find the FirstExample class due to the classpath (for some reason) so I executed the following command:
java -cp . FirstExample
And now it returns a new exception:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Now it can't find the JDBC Driver. This confuses me because for starters, I ran the exact same coding through Eclipse and it works as expected, and secondly, I went as far as to ensure that I execute the same class file that Eclipse is executing, and the command prompt still returns exceptions. I also went as far as to put the FirstExample file in a separate folder, just for the purpose of copying and pasting the MySQL Connector into the same folder, and I still get exceptions.
I just don't understand whats going on, can someone help me please?
Many thanks.
The file path to the connector is as followed:
C:\Program Files\MySQL\mysql-connector-java-3.1.14\mysql-connector-java-3.1.14-bin.jar
Hope this helps.
For testing purposes, I have placed the FirstExample class under the following path:
C:\java
This confuses me because for starters, I ran the exact same coding through Eclipse and it works as expected
This is because in Eclipse you add the libraries to the Build Path, and it will use all the libraries specified there in the classpath automatically when running your project. This can be noted here:
In order for you to execute your project using third party libraries from command line tools, you should specify the libraries manually in your classpath explicitly:
java -cp <path/to/mysql_jar/goes/here>:. FirstExample
By your comment:
the path to the MySQL file is: C:\Program Files\MySQL\mysql-connector-java-3.1.14\mysql-connector-java-3.1.14-bin.jar (...) I have placed the FirstExample class under C:\java
This should be the command line to use:
java -cp "C:\Program Files\MySQL\mysql-connector-java-3.1.14\mysql-connector-java-3.1.14-bin.jar; ." FirstExample
Note that it is better to store all the third party libraries in a single folder within your project, usually called lib, and put a reference to there. Assuming your current folder has a lib folder and all the third party libraries are copied there, the command line would be:
java -cp "lib\*; ." FirstExample
Use the next example to add your jars to the classpath:
java -cp "jdbc.jar;lib/*" my.package.FirstExample
You need to have the class com.mysql.jdbc.Driver (and all the imported classes) in the classpath too.
You should download the jar (http://dev.mysql.com/downloads/connector/j/5.0.html) and add it to the classpath.
The ClassNotFound Exception rises when there is an issue with the class name that you have written in Class.forName() or if the package is not set to the classpath variable. Make sure that you have added the jar file to the classpath ( C:............\jarfilename.jar;).
This is applicable for any JDBC Driver and jar files. The .jar files that are added to the classpath will not be visible to IDEs, in this case, you need to add the jar files to buildpath (in eclipse) or you can also copy the jar files to ext folder available in the Java installation folder.
Also note that the jar files of the DB Softwares may vary based on the DB software version that you are using for example if you are using the Oracle 11g, you need ojdbc6.jar file, in other versions of Oracle the number changes like ojdbc14.jar etc.

java sqlite exception

I made a Java application using netbeans and used sqlite as database
Everything works in netbeans but when i export the program to jar file and run it on another machine, an exception appeared when i try to connect sqlite database
The exception is about this line: Class.forName("org.sqlite.JDBC");
and the exception is: java.lang.ClassNotFoundException: org.sqlite.JDBC
I looked at all related threads in stackoverflow and no pure answer about this.
Thanks in advanced,
Just add the sqlite driver jar to your class path.
You application can't find the class org.sqlite.JDBC so it means a jar is missing in your class path.
Either include the sqlite jdbc driver in the jar file or make sure that you have it in your classpath. Add it as -classpath sqlite driver
Problem Solved
I had import the sqlite jar file for both compile time and run time. From netbeans -> project properties -> Libraries.
and Then i moved the exported jar file from dist folder in addition to lib folder to another machine .. and worked smoothly .. Thanks Guys up

I can't load the JDBC driver for MySQL

I've been trying to load the JDBC MySQL connector with the following code:
import java.sql.*;
public class dbTest{
public static void main(String[] args) throws SQLException, ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
}
}
And I keep getting a class not found exception:
java.lang.ClassNotFoundException
at edu.rice.cs.plt.reflect.PathClassLoader.findClass(PathClassLoader.java:148)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at dbTest.main(dbTest.java:6)
I have added the path to the driver (mysql-connector-java-3.1.14-bin.jar) to my classpath and double checked to make sure it was correct. I also added copies of the jar to the ext folder of my Java installation based on what I read from this article: http://www.developer.com/java/data/jdbc-and-mysql-installation-and-preparation-of-mysql.html
I also searched through posts of others who have had this problem, but all of the responses so far have been saying to add the connector jar to the classpath, which I have already done.
Any help would be greatly appreciated.
I have added the path to the driver
(mysql-connector-java-3.1.14-bin.jar)
to my classpath
The exception tells you that you didn't do it correctly.
How are you setting CLASSPATH? If it's an environment variable, you're going to learn that IDEs and app servers ignore it. Don't use it.
Don't put it in the /ext directory of your Java JDK, either.
The right way to do it depends on how you're using it:
If you're running inside an IDE like Eclipse or IntelliJ, you have to add the JAR to a library.
IF you're running in a command shell, use the -p option for javac.exe when you compile and java.exe when you run.
If you're using it in a web app, you can start by putting it in the WEB-INF/lib directory of your WAR file. If you're using a servlet/JSP engine like Tomcat 6, put it in the Tomcat /lib directory.
On IntelliJ this is how I solved this problem:
File > Project Structure > Libraries > +
Locate the jdbc connector. For me it was on C:\Users\MyName.InteliJIdea13\config\jdbc-drivers
There are two classpaths in java. Build path and run path. Build path is used when compiling .java files into .class files. In a language like C you have a linker stage that fills in all the missing symbols when you run the linker on a bunch of object files. Thats why for .exe(windows) or other native binaries(linux) there is no run path. Java is slightly different because the compiled .class definitions get loaded by the jvm as they are needed.
What the net out of this is that you have to supply a runtime classpath to the jvm. At the command line you use java.exe which searches a few places by default including $CLASSPATH, the current directory/lib, and whatever you supply to the -cp option.
IDEs are different from the command line because they are attempting to shield you from some of the nastiness of running java.exe and supplying the locations where all the .class files are(which would be onerous on a large project).
Most IDE's have some sort of "Run Configuration" tab that allows you to specify certain libraries or locations with classes that will be used when you run your application. Below is how to set the run path in eclipse,netbeans, and intellij.
http://javahowto.blogspot.com/2006/06/set-classpath-in-eclipse-and-netbeans.html
http://www.jetbrains.com/idea/webhelp/run-debug-configuration-application.html

Hibernate configuration file and Eclipse project export

I have a 3 projects under Eclipse : 1-CLIENT, 2-COMMON, 3-SERVER. The server project contains everything related to database managment (i.e. DAO...). I'm using hibernate and annotation for this project to access database. The common project contains also some objects commonly used by both the Server and the Client. Some of these objects are from the database. My Server project contains as well the HibernateUtils class that load the configuration file "hibernate.cfg.xml".
When I run the project under Eclipse, no problem, everything is going smoothly. Now comes the deployment... I'm exporting the server as a runnable jar file under Eclipse and the common project as a lib file. in the server jar file, I have the file "hibernate.cfg.xml".
When I launch the program, I'm ending up with an exception
Caused by: org.hibernate.HibernateException: /hibernate.cfg.xml not found
I've tried to force the filename in the configuration process using new AnnotationConfiguration().configure("XXXX/hibernate.cfg.xml"), but nothing is working !
Even when I copy the debug command line used to launch the program and paste it under a command dos window, it's not working...
What am I missing there ?
Hibernate searches for its configuration in places addressed in CLASS_PATH. i suggest you put your hibernate.cfg.xml in your source folder. this often prevent likely problems.
Another suggestion! don not export your project using eclipse export wizard, try to create an ant file to do so, or maven if you can...

Categories