Importante

Você está vendo a versão anterior da nova experiência da Alura que estamos preparando para você. Em breve, ela ganha uma identidade visual novinha totalmente pensada em potencializar seus estudos!

15
respostas

Failed to determine a suitable driver class

Troquei meu eclipse para uma versão mais nova. A anterior não aceitava as versões do java para compilar. Com isso não reconhecia o tipo Record. E eu estava criando os DTOs na mão. Agora com a versão mais nova está dando esse erro na inicialização do projeto:

2022-12-28T17:48:51.980-03:00 WARN 11675 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flyway' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Failed to instantiate [org.flywaydb.core.Flyway]: Factory method 'flyway' threw exception with message: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled. 2022-12-28T17:48:52.011-03:00 ERROR 11675 --- [ restartedMain] 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).

15 respostas

segue os arquivos:

pom:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>med.voll</groupId>
    <artifactId>api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>api</name>
    <description>API Rest da aplicação Voll.med</description>
    <properties>
        <java.version>18</java.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

        <dependency>
          <groupId>org.flywaydb</groupId>
          <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
          <groupId>org.flywaydb</groupId>
          <artifactId>flyway-mysql</artifactId>
        </dependency>

        <dependency>
          <groupId>com.mysql</groupId>
          <artifactId>mysql-connector-j</artifactId>
          <scope>runtime</scope>
        </dependency>

        <dependency>
          <groupId>jakarta.platform</groupId>
          <artifactId>jakarta.jakartaee-api</artifactId>
          <version>9.1.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

application.properties:

spring.datasource.url=jdbc:mysql://localhost/vollmed_api
spring.datasource.username=Klauber
spring.datasource.password=SerprO7955

Já estava funcionando até a listagem de médicos. na listagem que tive que trocar o eclipse.

Oi Klauber!

Tem uma dependência a mais no seu projeto. Remova ela do pom.xml:

<dependency>
    <groupId>jakarta.platform</groupId>
    <artifactId>jakarta.jakartaee-api</artifactId>
    <version>9.1.0</version>
</dependency>

Você instalou o Lombok nesse novo Eclipse? (no Eclipse ele não vem instalado por padrão).

Está com algum erro de compilação no projeto? Manda um print da estrutura do seu projeto.

instalei o Lombok.

segue a estrutura do projeto:

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

Está tudo certo. O erro é por não ter encontrado a propriedade spring.datasource.url no application.properties, mas no seu projeto ela está declarada.

Pode ser então que o projeto não pegou as mudanças. Verifica no menu superior do Eclipse Project se a opção Build Automatically está marcada.

Pare o projeto e vá no meu superior Project -> Clean para realizar um build no projeto, e depois clica com o botão direito no projeto e vá em: Maven -> Update project, para o maven atualizar o projeto. Depois disso rode novamenteo projeto para ver se resolveu.

O Build Automatically está marcado. Fiz novamente o Project -> Clean e o Maven -> Update project. Continua dando o mesmo erro.

O engraçado é que esse mesmo projeto estava funcionando corretamente antes. Só troquei o Eclipse e importei o projeto. Começou o erro.

Criei um novo workspace. recomecei o projeto do zero pelo start.spring.io e quando chegou no ponto da conexão com o banco deu o mesmo erro. fechei o eclipse e abri o projeto no eclipse antigo, voltei a versão do spring boot pra 2.7.7 e ele conseguiu conectar no banco. fechei tudo e abri o projeto com essa versão antiga no novo eclipse e deu o mesmo erro novamente. Agora eu buguei total... rsrs

4.0.0 org.springframework.boot spring-boot-starter-parent 2.7.7 med.voll api 0.0.1-SNAPSHOT api API Rest da aplicação Voll.med <java.version>11</java.version> org.springframework.boot spring-boot-starter-web

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-mysql</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>
![Insira aqui a descrição dessa imagem para ajudar na acessibilidade](https://cdn1.gnarususercontent.com.br/1/346434/d1e5f727-bb0a-4de5-9812-fdc2db3c91b1.png)

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

com a versão 2022-12 (4.26.0) do eclipse:

10:04:51.253 [Thread-0] DEBUG org.springframework.boot.devtools.restart.classloader.RestartClassLoader - Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@578998a

. __ _ __ _ _ /\ / _'_ _ _ _()_ _ __ _ \ \ \ ( ( )___ | ' | '| | ' / ` | \ \ \ \/ ___)| |)| | | | | || (| | ) ) ) ) ' |__| .|| ||_| |_, | / / / / =========||==============|__/=//// :: Spring Boot :: (v2.7.7)

2022-12-30 10:04:51.547 INFO 19555 --- [ restartedMain] med.voll.api.ApiApplication : Starting ApiApplication using Java 11.0.15 on serpro-1564354 with PID 19555 (/home/66930847534/workspaceSpringBoot/api/target/classes started by 66930847534 in /home/66930847534/workspaceSpringBoot/api) 2022-12-30 10:04:51.550 INFO 19555 --- [ restartedMain] med.voll.api.ApiApplication : No active profile set, falling back to 1 default profile: "default" 2022-12-30 10:04:51.597 INFO 19555 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable 2022-12-30 10:04:51.597 INFO 19555 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG' 2022-12-30 10:04:52.093 INFO 19555 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2022-12-30 10:04:52.104 INFO 19555 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 4 ms. Found 0 JPA repository interfaces. 2022-12-30 10:04:52.589 INFO 19555 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2022-12-30 10:04:52.603 INFO 19555 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-12-30 10:04:52.604 INFO 19555 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.70] 2022-12-30 10:04:52.656 INFO 19555 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-12-30 10:04:52.656 INFO 19555 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1058 ms 2022-12-30 10:04:52.728 WARN 19555 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flyway' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.flywaydb.core.Flyway]: Factory method 'flyway' threw exception; 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 2022-12-30 10:04:52.731 INFO 19555 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2022-12-30 10:04:52.753 INFO 19555 --- [ restartedMain] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2022-12-30 10:04:52.771 ERROR 19555 --- [ restartedMain] 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).

o mesmo projeto com a versão Version: 2018-09 (4.9.0) do eclipse:

10:21:41.445 [Thread-0] DEBUG org.springframework.boot.devtools.restart.classloader.RestartClassLoader - Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@578998a

. __ _ __ _ _ /\ / _'_ _ _ _()_ _ __ _ \ \ \ ( ( )___ | ' | '| | ' / ` | \ \ \ \/ ___)| |)| | | | | || (| | ) ) ) ) ' |__| .|| ||_| |_, | / / / / =========||==============|__/=//// :: Spring Boot :: (v2.7.7)

2022-12-30 10:21:41.733 INFO 20634 --- [ restartedMain] med.voll.api.ApiApplication : Starting ApiApplication using Java 11.0.15 on serpro-1564354 with PID 20634 (/home/66930847534/workspaceSpringBoot/api/target/classes started by 66930847534 in /home/66930847534/workspaceSpringBoot/api) 2022-12-30 10:21:41.734 INFO 20634 --- [ restartedMain] med.voll.api.ApiApplication : No active profile set, falling back to 1 default profile: "default" 2022-12-30 10:21:41.777 INFO 20634 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable 2022-12-30 10:21:41.778 INFO 20634 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG' 2022-12-30 10:21:42.271 INFO 20634 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2022-12-30 10:21:42.284 INFO 20634 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 4 ms. Found 0 JPA repository interfaces. 2022-12-30 10:21:42.794 INFO 20634 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2022-12-30 10:21:42.803 INFO 20634 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2022-12-30 10:21:42.803 INFO 20634 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.70] 2022-12-30 10:21:42.867 INFO 20634 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2022-12-30 10:21:42.867 INFO 20634 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1089 ms 2022-12-30 10:21:43.016 INFO 20634 --- [ restartedMain] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 8.5.13 by Redgate 2022-12-30 10:21:43.016 INFO 20634 --- [ restartedMain] o.f.c.internal.license.VersionPrinter : See what's new here: https://flywaydb.org/documentation/learnmore/releaseNotes#8.5.13 2022-12-30 10:21:43.016 INFO 20634 --- [ restartedMain] o.f.c.internal.license.VersionPrinter : 2022-12-30 10:21:43.021 INFO 20634 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2022-12-30 10:21:43.280 INFO 20634 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2022-12-30 10:21:43.302 INFO 20634 --- [ restartedMain] o.f.c.i.database.base.BaseDatabaseType : Database: jdbc:mysql://localhost/vollmed_api (MySQL 8.0) 2022-12-30 10:21:43.338 INFO 20634 --- [ restartedMain] o.f.core.internal.command.DbValidate : Successfully validated 3 migrations (execution time 00:00.013s) 2022-12-30 10:21:43.348 INFO 20634 --- [ restartedMain] o.f.core.internal.command.DbMigrate : Current version of schema vollmed_api: 3 2022-12-30 10:21:43.348 ERROR 20634 --- [ restartedMain] o.f.core.internal.command.DbMigrate : Schema vollmed_api has version 3, but no migration could be resolved in the configured locations ! 2022-12-30 10:21:43.349 INFO 20634 --- [ restartedMain] o.f.core.internal.command.DbMigrate : Schema vollmed_api is up to date. No migration necessary. 2022-12-30 10:21:43.423 INFO 20634 --- [ restartedMain] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default] 2022-12-30 10:21:43.473 INFO 20634 --- [ restartedMain] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.14.Final 2022-12-30 10:21:43.608 INFO 20634 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}

continuação do log pois estourou o limite de caracteres:

2022-12-30 10:21:43.608 INFO 20634 --- [ restartedMain] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final} 2022-12-30 10:21:43.715 INFO 20634 --- [ restartedMain] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect 2022-12-30 10:21:43.864 INFO 20634 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] 2022-12-30 10:21:43.872 INFO 20634 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2022-12-30 10:21:43.915 WARN 20634 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning 2022-12-30 10:21:44.198 INFO 20634 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2022-12-30 10:21:44.217 INFO 20634 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' 2022-12-30 10:21:44.224 INFO 20634 --- [ restartedMain] med.voll.api.ApiApplication : Started ApiApplication in 2.772 seconds (JVM running for 3.176)

Rodrigo,

criei a classe testaConexao que você sugeriu em outro tópico e funcionou aqui... mas com a aplicação continua dando o mesmo erro

import java.sql.Connection; import java.sql.DriverManager;

public class TestaConexao {

public static void main(String[] args) {
    try {
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/vollmed_api", "Klauber", "SerprO7955");
        System.out.println("conectado com sucesso!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Oi Kaluber!

Pois é, está muito estranho isso de funcionar em uma versão do Eclipse e em outra não :D

Consegue compartilhar o teu projeto (via GitHub ou link do Google Drive)?

Testei aqui e funcionou no meu Eclipse (versão 2022.06):

Insira aqui a descrição dessa imagem para ajudar na acessibilidade

A única coisa que alterei foi a versão do Java para a 17, e o username/password de acordo com o meu MySQL.