SpringBoot: Cannot load driver class: org.postgresql.Driver - postgresql

I have just created a new SpringBoot application (Java11) and am trying to connect to a Postgres database.
When I start the SpringBoot application, there is an error trying to connect to the database. The error reports that it Cannot load driver class: org.postgresql.Driver.
Question
How do I change my configuration below to get the SpringBoot application to connect to the database?
database version
PostgreSQL 12.6 on x86_64-apple-darwin16.7.0, compiled by Apple LLVM
version 8.1.0 (clang-802.0.42), 64-bit
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
application.properties
# pims datasource
spring.datasource.url=jdbc:postgresql://localhost:5432/pims
spring.datasource.username=postgres
spring.datasource.password=
spring.datasource.driverClassName=org.postgresql.Driver
#spring.datasource.driver-class-name=org.postgresql.Driver
#spring.jpa.database-platform=postgres
spring.jpa.show-sql=true
spring.datasource.dbcp2.test-while-idle=true
spring.datasource.dbcp2.validation-query=select 1
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
When I run the #SpringBootApplication class, SpringBoot starts to start up as expected, but gets the following error.
error
Error starting ApplicationContext. To display the conditions report
re-run your application with 'debug' enabled. 2021-06-15 11:58:51.770
ERROR 68967 --- [ main] o.s.boot.SpringApplication
: Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'dataSourceScriptDatabaseInitializer'
defined in class path resource
[org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]:
Unsatisfied dependency expressed through method
'dataSourceScriptDatabaseInitializer' 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
java.lang.IllegalStateException: Cannot load driver class:
org.postgresql.Driver
If I remove the following entry (i.e. don't define the driver in application.properties and just have the pom dependency):
spring.datasource.driverClassName=org.postgresql.Driver
I then get the following error:
Failed to load driver class org.postgresql.Driver in either of HikariConfig class loader or Thread context classloader

When I expend the external dependency tree, I didn't find any jar for postgressql. After reimport maven dependency, it is added correctly and problem is gone. It is fine now.

You do not need any specific configuration to connect database unless your repository and entity packages are not pulled from another dependency.
I would suggest you to check your connection between your computer and maven repository. You should be missing your postgre dependecy somehow.
(You also would try providing specific version of postgresql artifact)

Related

Ojdbc8 jars upgrade to 21.1.0.0 throws Nosuchmethod exception UCPservletContextListener init

Ojdbc8, ons, ucp jars are upgraded to 21.1.0.0 version. When trying to start the app on tomcat server, it's throwing Nosuchmethod exception. Logged in the Tomcat's localhost.log file. Application tries to establish DB connection during startup itself.
01-Jun-2021 15:59:56.641 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log 3 Spring WebApplication Initializers detected on classpath
01-Jun-2021 16:00:05.365 INFO localhost-startStop-1 org.apache.catalina.core.ApplicationContext.log Initializing Spring embedded WebApplicationContext
01-Jun-2021 16:00:19.397 SEVERE localhost-startStop-1 org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class [oracle.ucp.jdbc.UCPServletContextListener]
java.lang.NoSuchMethodException: oracle.ucp.jdbc.UCPServletContextListener.init
at java.lang.class.getConstructor(Unknown Source)
This is a known issue with ucp.jar in 21.1. It will be fixed in 21.3 when it's released. In the meantime, you can remove this class from the ucp.jar:
oracle/ucp/jdbc/UCPServletContextListener.class
From my experience, if you put jdbc/ucp jars to Tomcat's lib (which is recommended for productive system) and set provided scope for them in Maven, the problem will disappear.
Another option could be setting metadata-complete="true" in web.xml (read more here and here)
if you are using spring boot then you can use
<dependency>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>19.3.0.0</version>
</dependency>
this dependency or update your maven project.

Exception while building a war file via (maven install) for a spring boot project with mongodb

I am trying to build a spring-boot application with mongodb. I excluded the spring-boot-starter-data-mongodb dependency and using mongodb-driver 3.12.5.
My application.properties file contains only spring.data.mongodb.uri=connection _string.
With this above configuration I am unable to build a war file to deploy in server. It is giving the following error.
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo' defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.NoClassDefFoundError: com/mongodb/connection/DefaultClusterFactory
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.client.MongoClient]: Factory method 'mongo' threw exception; nested exception is java.lang.NoClassDefFoundError: com/mongodb/connection/DefaultClusterFactory
Caused by: java.lang.NoClassDefFoundError: com/mongodb/connection/DefaultClusterFactory
Caused by: java.lang.ClassNotFoundException: com.mongodb.connection.DefaultClusterFactory
please help, thanks.
This is issue was solved by replacing the mongodb-driver dependency with mongodb-java-driver dependency
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.6.3</version>
</dependency>
as for the situation i faced i did not add a dependency that i am using in the application. that was the mistake.

springboot rest swagger :error in initialising bean

I am using swagger to document my spring boot rest application
Using
spring-boot-starter-web
spring-boot-starter-data-rest
springfox-swagger2 2.9.2
springfox-swagger 2.9.2
Code is building fine but when I run it it is throwing error below
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration
$EnableWebMvcConfiguration.class]:
Unsatisfied dependency expressed through method 'requestMappingHandlerMapping' parameter 1;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration
$EnableWebMvcConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.format.support.FormattingConversionService]:
Factory method 'mvcConversionService' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'jsonSchemaConverter' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.rest.webmvc.json.PersistentEntityToJsonSchemaConverter]:
Factory method 'jsonSchemaConverter' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'defaultConversionService' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.format.support.DefaultFormattingConversionService]:
Factory method 'defaultConversionService' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'repositoryInvokerFactory' defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.repository.support.RepositoryInvokerFactory]:
Factory method 'repositoryInvokerFactory' threw exception;
nested exception is java.lang.NoSuchMethodError: org.springframework.plugin.core.PluginRegistry.of(Ljava/util/List;)Lorg/springframework/plugin/core/PluginRegistry;
I had the same problem. Here is my fix:
TL/DR:
Springfox uses an outdated version of spring-plugin-core and is incompatible with spring boot 2.2.5. Springfox seems to be no longer maintained; migrate to a different spring-swagger-bridge, such as Springdoc-openapi: https://springdoc.github.io/springdoc-openapi-demos/
Relevant output
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.data.repository.support.RepositoryInvokerFactory]:
Factory method 'repositoryInvokerFactory' threw exception; nested exception is java.lang.NoSuchMethodError:
'org.springframework.plugin.core.PluginRegistry org.springframework.plugin.core.PluginRegistry.of(java.util.List)'
From NoSuchMethodError: org.springframework.plugin.core.PluginRegistry.getPluginOrDefaultFor:
...a wild guess would be that the last working version of springfox (working for you and us) was compiled with a Spring boot version inferior to 2.2.2. That boot version had a different method signature for getPluginOrDefaultFor (or possibly the method didn't exist at all).
Cause
springfox imports version 1.2.0 of the spring-plugin-core. Spring Boot 2.2.5 needs version 2.0.0.RELEASE
springfox wins the import lottery; test fails b/c Spring Boot can't find its method.
explicitly importing 2.0.0.RELEASE makes springfox die.
springfox' latest version is 2.9.2; even the 3.0.0-SNAPSHOT does not fix the issue: https://github.com/springfox/springfox/issues/2932
Solution
Springfox is apparently abandoned:
Springfox swagger not working in spring boot 2.2.0
Solution is to migrate to a different spring-swagger bridge.
Most likely candidate is Springdoc-openapi:
https://springdoc.github.io/springdoc-openapi-demos/
User experience (last comment from https://github.com/springfox/springfox/issues/2932):
Yes I ended up following the links to 'springDoc' and found a
quick tutorial.
It was super easy to setup all in the pom.xml file.
Just one tweak was needed
<!-- org.springdoc for swagger setup -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-core</artifactId>
<version>1.1.49</version>
<exclusions>
<exclusion>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.1.49</version>
</dependency>

spring-data-dynamodb, aws-java-sdk-dynamodb and JPA not working together

We are developing a micro-service based on Spring that need to work with both DynamoDB and MySQL. As an example I took this simple "DynamoDB in a Spring" example and everything worked fine. Then I wanted to add the MySQL part but as soon as I added this to the pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Spring stoped working complaining that the productInfoRepository isn't a managed type:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productInfoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.baeldung.spring.data.dynamodb.model.ProductInfo
basePackageClasses of #EnableJpaRepositories and #EnableDynamoDBRepositories should be mutually exclusive.

javax.persistence jar is not loaded into tomcat

I'm trying to run JPA servlet on Tomcat 8.
From my servlet I call method of a class named QueryDB.class located in another Eclipse project (JPA project, not WEB project).
But tomcat throws
SEVERE: Servlet.service() for servlet [MyRESTService] in context with path [/AutomationWeb] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: javax/persistence/Persistence] with root cause
java.lang.ClassNotFoundException: javax.persistence.Persistence
at java.net.URLClassLoader$1.run(Unknown Source)
...
Exception is thrown at line EntityManagerFactory emf = Persistence.createEntityManagerFactory( "AutomationDB_JPA" ); in QueryDB.class
I'm using Eclipse Mars with Maven. I have EclipseLink in my pom.xml defined:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.1</version>
</dependency>
I have following jars in my Application's WEB-INF/lib:
eclipselink-2.6.1.jar
javax.persistence-2.1.0.jar , it has javax/persistence/Persistence.class inside
There is no other SEVERE messages in the tomcat log.
What's wrong with this setup?
I also tried adding the persistence jar to apache-tomcat-8.0.28\lib , but got the same error.
Update: I moved Persistence.createEntityManagerFactory call to the servlet itself and got no classloader exception. So the question changes: why classloader used for QueryDB.class is different from servlet's classloader? Also, why classloader used in QueryDB.class does not see the Persistence.class, which is seen by the servlet's classloader?
Ok I've found a solution.
Excluded my JPA project from tomcat VM classpath
Converted my JPA project to the Utility project
Modified Deployment Assembly in my Web project properties so that it
will accept JPA project as .jar archive into WEB-INF/lib
I have no classloader exception anymore.