Spring Boot JPA MySQL : Failed to determine a suitable driver class - mysql

I am creating an application using Spring Boot JPA, I am using MySQL as a database.
Following is my application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
I have added following dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
When I checked in debug logs I can see mysql java connector in my classpath but still I am getting following errors
2019-07-29 10:03:00.742 INFO 10356 --- [ main]
o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring
embedded WebApplicationContext 2019-07-29 10:03:00.742 INFO 10356 ---
[ main] o.s.web.context.ContextLoader : Root
WebApplicationContext: initialization completed in 1534 ms 2019-07-29
10:03:00.789 WARN 10356 --- [ main]
ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration':
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in class path resource
[org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException:
Failed to determine a suitable driver class 2019-07-29 10:03:00.789
INFO 10356 --- [ main]
o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2019-07-29 10:03:00.805 INFO 10356 --- [ main]
ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report
re-run your application with 'debug' enabled. 2019-07-29 10:03:00.805
ERROR 10356 --- [ main]
o.s.b.d.LoggingFailureAnalysisReporter :
*************************** APPLICATION FAILED TO START
Description:
Failed to configure a DataSource: 'url' attribute is not specified and
no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following: If you want an embedded database (H2, HSQL or
Derby), please put it on the classpath. If you have database settings
to be loaded from a particular profile you may need to activate it (no
profiles are currently active).

Spring Boot auto-configuration tries to configure the beans automatically based on the dependencies added to the classpath. Since you have the JPA dependency on your classpath, Spring Boot tries to automatically configure a JPA DataSource. The problem is, you haven’t given Spring the complete information it needs to perform the auto-configuration.
Add this missing property to your application.properties file, so that spring can autoconfigure
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Another way you can define your data source programmatically, by using the utility builder class DataSourceBuilder. For that you need to provide the database URL, username, password, and the SQL driver information to create your data source:
#Configuration
public class DatasourceConfig {
#Bean
public DataSource datasource() {
return DataSourceBuilder.create()
.driverClassName("com.mysql.cj.jdbc.Driver")
.url("jdbc:mysql://localhost:3306/myDb")
.username("root")
.password("pass")
.build();
}
}

I had the same problem, I resolved it by doing right click on the project, maven/update project, then you should select your project and accept.

I had this problem too. My solution is : open module settings,and select resources,and right click it ,and select "Test Resources". Then it's solved.

Spring Autoconfigure looks for 2 properties to load the appropriate driver,
spring.datasource.driverClassName (in this case the value would be 'com.mysql.cj.jdbc.Driver' from MySQL connector 4.4.1.3 onwards)
spring.datasource.url (in this case it is jdbc:mysql://localhost:3306/mydb)
Actually Spring Autoconfigure just need spring.datasource.url and it can derive the driver class name from there.

Your application organization looked like :
Commons
->
Module1
Commons was a parent to Module1.
I had created a BaseEntity having JPA annotations in my commons module. The commons dependency was specified as
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Once I added the provided
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<scope>provided</scope>
</dependency>
The issue got resolved for me. Unfortunately

change:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
to:
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/mydb

It was some mistake in my configuration which I couldn't detect, I re-created same project and things started working

Related

Cannot load driver class: com.mysql.cj.jdbc.Driver

My Spring Boot Project trying connect to MYSQL database with driver mysql-connector-java.
I have import newest mysql driver and spring-boot-starter-data-jpa
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
I have configured database connection in application.properties file
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=somethingfunny
spring.datasource.password=somethingfunny
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true
MYSQL version is 8.0.26
Spring boot version 2.6.2
When run project with Intellij I get error
Caused by: org.springframework.beans.BeanInstantiationException:
Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory
method 'dataSource' threw exception; nested exception is
java.lang.IllegalStateException: Cannot load driver class:
com.mysql.cj.jdbc.Driver at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
~[spring-beans-5.3.14.jar:5.3.14] at
org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653)
~[spring-beans-5.3.14.jar:5.3.14] ... 35 common frames omitted Caused
by: java.lang.IllegalStateException: Cannot load driver class:
com.mysql.cj.jdbc.Driver at
org.springframework.util.Assert.state(Assert.java:97)
~[spring-core-5.3.14.jar:5.3.14] at
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:241)
~[spring-boot-autoconfigure-2.6.2.jar:2.6.2] at
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:193)
~[spring-boot-autoconfigure-2.6.2.jar:2.6.2] at
org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:48)
~[spring-boot-autoconfigure-2.6.2.jar:2.6.2] at
org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari.dataSource(DataSourceConfiguration.java:90)
~[spring-boot-autoconfigure-2.6.2.jar:2.6.2] at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:na] at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
~[na:na] at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
~[na:na] at
java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
~[spring-beans-5.3.14.jar:5.3.14] ... 36 common frames omitted
I have refered the post about Cannot load driver class: com.mysql.jdbc.Driver (NOT com.mysql.cj.jdbc.Driver), I cannot apply for my project because my project get error when using com.mysql.cj.jdbc.Driver but not com.mysql.jdbc.Driver.
I also refered this post Cannot load driver class: com.mysql.cj.jdbc.Driver. But i can not find correct answer(the answer is marked corrected) for this error.
How to fix this error ?
1) Use this dependency in pom.xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
2) Use this property in your application.properties file
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
I have fix this issue. In Intellij right click to project, choose maven, choose reload project. Now Intellij will add mysql driver to the project
Going off of one of the above answers https://stackoverflow.com/a/70514438/14111809, but with a Gradle instead of Maven (in IntelliJ IDE), this fixed the issue for me:
Have you checked which version of MySQL connector do you have?
Since you haven't specified the version in your pom.xml, there is a chance that it pulled version 5 and now it is complaining about that .cj which is required for version 8.
That might be the reason why is it working without .cj ( com.mysql.jdbc.Driver ), because it pulled the version 5.
Manually add the version in your pom.xml and keep .cj as it is.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
After that make sure that you pull your dependencies.
But make sure that you check in your project if you do have ONLY version 8 after "mvn clean install".
As of the picture that you shared "mysql version", that means nothing, the exception is regarding mysql-connector jar, it has nothing to do with the workbench, you can still have workbench version 5, and use mysql-connector jar version 8, it will make no difference.
In any version of mysql workbench ( 5 or 8 ):
mysql-connector 8 jar = requires .cj
mysql-connector 5 jar = does not require .cj
The only thing that you need to do is define the version of mysql-connector-java in your pom.xml
Fix the line that sets jdbc driver class as below: I don't think it matters but driver-class-name is more common. And check if your build file is up to date. Might as well try re-building using pom.xml
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Hibernate db url configuratin issue with UTC mapping

Getting below error message while configuring db details in hibernate.cfg.xml file.
Sensing a mistake in jdbc url, But not able to find the actual cause.
Caused by: com.mysql.cj.exceptions.WrongArgumentException: No timezone
mapping entry for
'UTC;allowPublicKeyRetrieval=true;useLegacyDatetimeCode=false' at
snippet of hibernate.cfg.xml file
<!-- JDBC Database connection settings -->
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC;allowPublicKeyRetrieval=true</property>
Using below tag
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC</property>
and replacing javax.persistance with latest maven version helped me. maven entry as below
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>

Error Could not get JDBC Connection when java web tries connect to mariadb galera cluster

I have a java webapp with spring mvc, mybatis, jndi and tomcat
Additionally, On Tomcat context.xml, I defined:
<Resource auth="Container"
driverClassName="com.mysql.jdbc.Driver"
maxIdle="100" maxTotal="100"
name="jdbc/dbExample"
password="dbpass"
type="javax.sql.DataSource"
url="jdbc:mariadb:sequential://192.1.1.12,192.1.1.13,192.1.1.14:3306/dbExample"
username="dbuser"/>
Also, in pom file I have the following dependency:
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.7.6</version>
</dependency>
The database is mariadb galera cluster multimaster.
Then when I test the web app I got the following error:
Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver'] with root cause java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
What can I do?

cleardb (mySQL) connection problem witth Heroku (spring)

I am creating a springboot application which has data stored in a mysql database. I have used cleardb as an add-on and have deployed the app to Heroku. When I run the app (i.e heroku open), the main page (index.html) displays successfully as it does not require access to the mySQL database. However, all of the pages that do require access to the mySQL database do not display and return the error below:
There was an unexpected error (type=Internal Server Error, status=500).
Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Here is some of my code:
Databaseconfig
#Configuration
public class DatabaseConfig {
#Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost/NBA");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
}
pom.xml plugins
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
database_url (heroku config)
CLEARDB_DATABASE_URL: mysql://b---------9:9--------#us-cdbr-iron-east-05.cleardb.net/heroku_f61b74207636b77?reconnect=true
DATABASE_URL: 'mysql://b---------9:9--------#us-cdbr-iron-east-05.cleardb.net/heroku_f61b74207636b77?reconnect=true'
Some things to take note of:
My application.properties file is currently empty.
The application runs perfectly when I run it on localhost:8080.
Any and all help would be greatly appreciated.
For your case your must change the dataSource configuration according your database_url(heroku config):
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://us-cdbr-iron-east-05.cleardb.net/heroku_f61b74207636b77?reconnect=true");
dataSource.setUsername("b05ee51c5eec59");
dataSource.setPassword("94a4e9eb");
I also suggest you to use following in your application.properties instead of using datasource bean:
spring.datasource.username=
spring.datasource.password=
spring.datasource.url=
Also very important: change your database password in the heroku and dont write it on the internet

Jackson #JsonSerialize ignored in Jboss 7.1.1 if maven dependecy set to provided

I have Jax-rs endpoint deployed in WAR archive on JBoss 7.1.1.
In its JSON response I don't want my null field name to be included, so I put #JsonSerialize on it.
class MyResponse {
private Long id;
#JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
private String name;
private List<String> addresses;
// getters and setters
}
My pom.xml has the following
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.3.2.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.3.2.Final</version>
<scope>provided</scope>
</dependency>
When the scope for resteasy-jackson-provider is set to provided it ignores the annotation and returns null in JSON response. However when I remove the scope from maven dependency - it works.
From the page here https://docs.jboss.org/author/display/AS71/Implicit+module+dependencies+for+deployments it looks like JBoss should autoload this module if Jax-RS deployment found.
Now I don't know if this is a bug and if I should really include this dependency (NOT keeping it provided). Or maybe I'm doing something wrong there?
You need to make sure to create a JBoss Deployment Structure descriptor.
Since this is a Maven project I assume it would be under src/main/webapp/WEB-INF/jboss-deployment-structure.xml
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.0">
<deployment>
<dependencies>
<module name="org.codehaus.jackson.jackson-core-asl" />
<module name="org.codehaus.jackson.jackson-mapper-asl" />
</dependencies>
</deployment>
</jboss-deployment-structure>
This will allow the built-in support for RESTEasy and Jackson to work correctly in JBoss 7.1.x or JBoss EAP 6.x. Without this descriptor RESTEasy will use the Jettison provider.