I'm working on a Java EE project (configuration below) and I face what seems to be a regular exception: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
.
I'm working with Eclipse, an embedded Tomcat 7 and Maven, and even if the driver is found for the tests, it is not found by Tomcat.
I searched for some answers 1, 2 and 3 but the advices were unclear:
It is recommended to change the mysql-connector-java
to provided
, and manually copy the dependency in the server (not clear how).
Yet I do not understand why I should exclude the dependency for deployment (scope provided
) and add it manually, isn't it contradictory?
After reading the Maven documentation, I feel like the running environment would need the dependency, and therefore the compile
scope is best suited.
Well as you can see I'm trying to figure these things out, so I would rather have an explanation than a magic fix.
The configuration:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
The database properties:
URL = jdbc:mysql://127.0.0.1:3306/XXX-db?zeroDateTimeBehavior=convertToNull
USERBD = XXX
PASSWORDBD = XXX
DRIVER = com.mysql.jdbc.Driver
The properties loading:
static {
try {
Properties databaseProperties = new Properties();
InputStream inputStream = DatabaseConnection.class.getClassLoader()
.getResourceAsStream(PROPERTIES_FILE);
if (inputStream != null) {
databaseProperties.load(inputStream);
} else {
throw new FileNotFoundException(
"property file '" + PROPERTIES_FILE + "' not found in the classpath");
}
Class.forName(databaseProperties.getProperty("DRIVER"));
USERBD = databaseProperties.getProperty("USERBD");
PASSWORDBD = databaseProperties.getProperty("PASSWORDBD");
URL = databaseProperties.getProperty("URL");
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}