SpringBoot não cria tabelas no MySql

Tenho um projeto em SpringBoot conectando em um banco MySql 8.0.31 (WampServer 3.3.0).
O projeto estava apresentando o seguinte erro:

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-03-24T13:16:52.572-03:00 ERROR 5192 --- [  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).

A partir daí eu inseri a seguinte anotação na minha classe “application”:
@SpringBootApplication (exclude = {DataSourceAutoConfiguration.class }) e parou de apresentar o erro, mas não está criando as tabelas no banco.
Será que pode ter relação dessa anotação com a não criação das tabelas no banco?

Meu application.properties:

#Configurações do JPA:

spring.datasource.url=jdbc:mysql://localhost:3306/minas_cafe?createDatabaseIfNotExist=true

spring.datasource.username=root

spring.datasource.password=359423

spring.jpa.generate-ddl=true

spring.jpa.hibernate.ddl-auto=validate

#Porta de trabalho do Tomcat

server.port=${port:8080}

#Exibe os comandos SQL

spring.jpa.show-sql=true

#Especifica qual o banco de dados você usará

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#Enable spring data repos

spring.data.jpa.repositories.enabled=true

spring.jpa.database=mysql

Pom.XML:

<?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.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.cafe</groupId>
	<artifactId>Minas</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Minas</name>
	<description>Projeto de Automatização de Processos de Com. e Prest. Serviços Minas Café</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.6.15.Final</version>
		</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.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>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!--<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>-->
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Classe application:

package com.cafe.api;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

//Desabilitando a segurança do SpringBoot - Informa para o spring-boot excluir/desativar a autoconfiguração de DataSource
@SpringBootApplication (exclude = {DataSourceAutoConfiguration.class }/*, scanBasePackages= {"com.minascafe.api.repositories"}*/)
//@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) //tenta configurar automaticamente seu aplicativo Spring com base nas dependências jar que você adicionou
//E exclui o carregamento do bean da fonte de dados

//@EntityScan(basePackages = {"com.minascafe.api.entities"}) //Onde estão sendo criadas as classes Java mapeadas com @Entity
//@ComponentScan(basePackages = {"com.minascafe.api.repositories"})
// //@EnableJpaRepositories(basePackages = {"com.minascafe.api.repositories"})

public class MinasApplication {

	public static void main(String[] args) {
		SpringApplication.run(MinasApplication.class, args);
	}	

	   //gera um componente do Spring

	   @Bean
		 public CommandLineRunner commandLineRunner() { //Executa automaticamente junto com o Spring
			
	        return args ->{

	            System.out.println("Executando o primeiro teste do projeto perfeitamente!");

	     };		    
	  }

}

Alguém poderia me ajudar?

O problema com o dataSource pode ser algum bug na IDE já que vc já adicionou o driver ao pom.xml.

Por isso eu sugiro que vc de um clean no seu projeto e tente fazer o rebuild novamente.

Eu fiz um teste usando o seu pom.xml sem adicionar o driver do MySQL e deu o mesmo erro no dataSource, mas foi só eu adicionar o driver que este erro sumiu.

Nisso apareceu outro erro por causa da compatibilidade entre versões. Este erro eu corrigi removendo a seguinte dependência:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.6.15.Final</version>
</dependency>

Como vc está trabalhando com Spring Boot, vc não precisa adicionar o Hibernate manualmente e nem especificar a versão.


Não se esqueça de trocar isso:

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })

Por isso:

@SpringBootApplication

Senão o Spring não vai fazer fazer as configurações para trabalhar com o banco de dados.

Se eu removo “(exclude = { DataSourceAutoConfiguration.class })” da anotação @SpringBootApplication, apresenta o seguinte erro:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
:: Spring Boot ::               (v3.0.4)

2023-03-29T14:44:43.220-03:00 INFO 1948 --- [  restartedMain] com.cafe.api.MinasApplication           : Starting MinasApplication using Java 17.0.6 with PID 1948 (C:\Users\Edson\Documents\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasCafe\target\classes started by Edson in C:\Users\Edson\Documents\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasCafe)
2023-03-29T14:44:43.235-03:00 INFO 1948 --- [  restartedMain] com.cafe.api.MinasApplication            : No active profile set, falling back to 1 default profile: "default"
2023-03-29T14:44:43.327-03:00 INFO 1948 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2023-03-29T14:44:43.327-03:00 INFO 1948 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor :  For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2023-03-29T14:44:44.431-03:00 INFO 1948 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-03-29T14:44:44.466-03:00 INFO 1948 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate :  Finished Spring Data repository scanning in 20 ms. Found 0 JPA repository interfaces.
2023-03-29T14:44:45.279-03:00  INFO 1948 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  :  Tomcat initialized with port(s): 8080 (http)
2023-03-29T14:44:45.297-03:00 INFO 1948 --- [  restartedMain] o.apache.catalina.core.StandardService  : Starting service [Tomcat]
2023-03-29T14:44:45.297-03:00 INFO 1948 --- [  restartedMain] o.apache.catalina.core.StandardEngine    :  Starting Servlet engine: [Apache Tomcat/10.1.5]
2023-03-29T14:44:45.404-03:00 INFO 1948 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       :  Initializing Spring embedded WebApplicationContext
 2023-03-29T14:44:45.404-03:00 INFO 1948 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2076 ms
2023-03-29T14:44:45.490-03:00 WARN 1948 --- [  restartedMain] ConfigServletWebServerApplicationContext :  Exception encountered during context initialization - cancelling refresh attempt: 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: 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
2023-03-29T14:44:45.495-03:00 INFO 1948 --- [  restartedMain] o.apache.catalina.core.StandardService  : Stopping service [Tomcat]
2023-03-29T14:44:45.532-03:00 INFO 1948 --- [  restartedMain].s.b.a.l.ConditionEvaluationReportLogger :

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-03-29T14:44:45.577-03:00 ERROR 1948 --- [  restartedMain] .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).

Tá, mas e quanto ao resto das minhas sugestões?

Bem, eu removi a dependência do hibernate, dei um ‘clean’ no projeto. Mas, ao menos com esse ‘exclude’ na anotação @SpringBootApplication não cria as tabelas no banco. E se eu removo esse ‘exclude’, apresenta o erro mencionado acima.

Na realidade está dizendo que o atributo ‘url’ no datasource não está especificado, mas no meu application.properties está definido “spring.datasource.url=jdbc:mysql://localhost:3306/minas_cafe?createDatabaseIfNotExist”

Hum… É estranho.

Se vc quiser, coloca este projeto no GitHub para eu clonar e experimentar aqui.

Se não me engano este é o driver antigo, como você está usando a dependência mais recente do MySQL tente alterar para:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

É o contrário: https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-api-changes.html

  • The name of the class that implements java.sql.Driver in MySQL Connector/J has changed from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver. The old class name has been deprecated.
1 curtida

Isso mesmo, essa questão eu já tinha verificado.

Pessoal, consegui resolver aqui. Vi em algum lugar que o Eclipse está apresentando esse problema com alguns desenvolvedores. Migrei meu projeto para o Intellij, dei uma repaginada no meu pom.xml e funcionou normalmente. Executou sem apresentar erros e criou as tabelas no banco de dados (MySql) conforme eu precisava.
Fiquei decepcionado com o Spring Tool Suite (Eclipse). :pensive: :grimacing:

Muito obrigado a todos pela ajuda!

1 curtida