maven pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Test</groupId>
<artifactId>Test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Test</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.18</version>
</dependency>
</dependencies>
In code Im trying to execute Class.forName("com.mysql.jdbc.Driver")
.
I get this:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
But I have checked I have mysql.jar in jboss-as-7.0.2.Final\standalone\deployments\Test.war\WEB-INF\lib
and it has com.mysql.jdbc.Driver class.
I had a slightly different use case. I was using apache's BasicDataSource in a stand-alone application.
I got this exception because I was calling
setDriverClassName
withcom.mysql.jdbc.Driver.class.toString()
instead of"com.mysql.jdbc.Drive"
as a String (so compile time check ensures that there is no typo or Driver's location didn't change in a version upgrade... etc).But!
When you look Driver's implementation it has a static initialization block:
When I wrote
com.mysql.jdbc.Driver.class.toString()
this initialization block executed too early and caused later on misleadingClassNotFoundException
to be thrown. Once I switched to"com.mysql.jdbc.Driver"
my application started to work.This is a case when static becomes evil :)
As a rule you should not be including your JDBC drivers in your war file.
I suggest you mark the driver as provided and add it to the lib directory of the server.
PS. I'm not sure why you would be using
in your code. Why not let the contain manage your connections and transactions?
It seems you are using JBoss AS7. Check instructions here: https://community.jboss.org/wiki/DataSourceConfigurationInAS7
Basically, you should
Class.forName() is an idiom commonly used when data sources are not provided by the container. In modern Java EE servers, they are provided.
This error occurred because your mysql jar is not on your run-time class-path. If you are using maven,