Solucionado (ver solução)
Solucionado
(ver solução)
19
respostas

SpringBoot não cria tabelas no MySql

Estou desenvolvendo uma aplicação em Spring Boot e não estou conseguindo fazer com que crie ou atualize tabelas no banco MySql (Wamp Server). Já anotei a classe "Application" com a anotação @EntityScan(basePackages = {"caminho da pasta que contém minhas classes marcadas com @Entity"}), já defini o driver do MySql no application.properties (spring.datasource.url= jdbc:mysql://localhost:3306/minas_cafe) e defini para criar e atualizar as entidades no banco automaticamente no properties (spring.jpa.hibernate.ddl-auto=update) e não cria as tabelas no MySql.

Alguém pode me dar uma luz? Desde já agradeço o auxílio da comunidade!

Meu application.properties:

#logging.level.com.minascafe=DEBUG

#gerenciamento de conexões nos bancos de dados
spring.datasource.type=com.zaxxer.hikari.HikariDataSource 

#MySQL - definindo a conexão
server.port=${port:8080}
spring.datasource.url= jdbc:mysql://localhost:3306/minas_cafe
spring.datasource.username=root
spring.datasource.password=359423
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#Cria e atualiza entidades no banco automaticamente
spring.jpa.hibernate.ddl-auto=create

#Exibe os comandos SQL

#Exibe as queries executadas pela aplicação Java 
spring.jpa.properties.hibernate.show-sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.type=trace
spring.jpa.show-sql=true

#habilitando o flyway
spring.flyway.enabled=true

Meu script em src/resources/db/migration/V01__create_tables.sql:

CREATE TABLE IF NOT EXISTS `cad_cafe_coco` (
  `lote` int(7) NOT NULL AUTO_INCREMENT,
  `produtor` varchar(50) NOT NULL,
  `status` varchar(3) DEFAULT NULL,
  `data` date NOT NULL,
  `sacos` int(4) NOT NULL,
  `quilos` float NOT NULL,
  `baracao` int(4) DEFAULT NULL,
  `subproduto` varchar(70) DEFAULT NULL,
  `numero_nota` int(11) DEFAULT NULL,
  `classificacao` varchar(5) DEFAULT NULL,
  `catacao` int(11) DEFAULT NULL,
  `peneira` int(11) DEFAULT NULL,
  `lancado` varchar(3) DEFAULT NULL,
  `observacoes` varchar(140) DEFAULT NULL,
  `referencia` varchar(7) DEFAULT NULL,
  `meieiro` VARCHAR(40) DEFAULT NULL,
  `porcentagem_produtor` int(2),
  `porcentagem_meieiro` int(2),
  PRIMARY KEY (`lote`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `cad_cafe_beneficiado` (
  `lote` int(7) NOT NULL AUTO_INCREMENT,
  `produtor` varchar(50) NOT NULL,
  `status` varchar(3) DEFAULT NULL,
  `data` date NOT NULL,
  `sacas` int(4) NOT NULL,
  `quilos` float NOT NULL,
  `baracao` int(4) DEFAULT NULL,
  `subproduto` varchar(70) DEFAULT NULL,
  `numero_nota` int(11) DEFAULT NULL,
  `classificacao` varchar(5) DEFAULT NULL,
  `catacao` int(11) DEFAULT NULL,
  `peneira` int(11) DEFAULT NULL,
  `lancado` varchar(3) DEFAULT NULL,
  `observacoes` varchar(140) DEFAULT NULL,
  `meieiro` varchar(40) DEFAULT NULL,
  `porcentagem_produtor` int(2),
  `porcentagem_meieiro` int(2),
  PRIMARY KEY (`lote`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `cad_cafe_maquina` (
  `lote` int(5) NOT NULL AUTO_INCREMENT,
  `produtor` varchar(50) NOT NULL,
  `status` varchar(3) DEFAULT NULL,
  `data` date NOT NULL,
  `sacas` int(3) NOT NULL,
  `quilos` float NOT NULL,
  `baracao` int(1) DEFAULT NULL,
  `subproduto` varchar(70) DEFAULT NULL,
  `numero_nota` int(4) DEFAULT NULL,
  `classificacao` varchar(5) DEFAULT NULL,
  `catacao` int(2) DEFAULT NULL,
  `peneira` int(2) DEFAULT NULL,
  `lancado` varchar(3) DEFAULT NULL,
  `referencia` varchar(7) DEFAULT NULL,
  `observacoes` varchar(140) DEFAULT NULL,
  `meieiro` VARCHAR(40),
  `porcentagem_produtor` int(2),
  `porcentagem_meieiro` int(2),
  PRIMARY KEY (`lote`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `ficha_produtor` (
  `nome` varchar(50) NOT NULL,
  `apelido` varchar(20) DEFAULT NULL,
  `cpf` int(11) NOT NULL,
  `telefone` int(11) DEFAULT NULL,
  `data` date NOT NULL,
  `entrada_saida` varchar(80) DEFAULT NULL,
  `lote` varchar(7) NOT NULL,
  `duro` float DEFAULT NULL,
  `riado` float DEFAULT NULL,
  `rio` float DEFAULT NULL,
  `escolha` float DEFAULT NULL,
  `renda` int(2) DEFAULT NULL,
  `humidade` int(2) DEFAULT NULL,
  `valor_total` float DEFAULT NULL,
  `id` int(11) NOT NULL DEFAULT '0',
  `banco` VARCHAR(25) DEFAULT NULL,
  `agencia` VARCHAR(5) DEFAULT NULL,
  `operacao` VARCHAR(3) DEFAULT NULL,
  `tipo_conta` VARCHAR(14) DEFAULT NULL,
  `numero_conta` VARCHAR(13) DEFAULT NULL,
  `nome_correntista` VARCHAR(50) DEFAULT NULL,
  `chave_pix` VARCHAR(60) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
19 respostas

Sugestão: verifique se a anotação @Entity está presente em todas as classes de "model" que você deseja criar como tabelas no banco de dados. Outra coisa a verificar é se as entidades estão localizadas no caminho correto especificado na anotação @EntityScan.

Olá Otávio,

sim, eu já verifiquei essas duas questões e estão corretas.

Desde já agradeço sua ajuda!

Desabilitei o flyway e mantive somente o JPA. Meu application.properties está assim:

#spring.profiles.active=default

#Configurações do JPA:

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/minas_cafe?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=359423
server.port=8080
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#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
# 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.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.minascafe</groupId>
    <artifactId>MinasCafe</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>MinasCafe</name>
    <description>Projeto de Informatização de Processos da Minas Café</description>
    <properties>
        <java.version>17</java.version>
    </properties>

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

        <!-- web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>  <!--Carrrega o servidor TomCat -->
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Hibernate validator -->
        <dependency>
            <groupId>org.springframework.boot</groupId> <!--realiza validações-->
            <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>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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    <!--    <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency> -->

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.7.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-params</artifactId>
        <version>5.7.0</version>
        <scope>test</scope>
    </dependency>        
    </dependencies>

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

</project>

Aí estava gerando o seguinte erro:

2023-03-21T13:42:35.134-03:00 INFO 7652 --- [  restartedMain] com.minascafe.api.MinasCafeApplication  : Starting MinasCafeApplication using Java 17.0.6 with PID 7652 (C:\Users\Edson\OneDrive\Documentos\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasCafe\target\classes started by Edson in C:\Users\Edson\OneDrive\Documentos\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasCafe)
2023-03-21T13:42:35.156-03:00 INFO 7652 --- [  restartedMain] com.minascafe.api.MinasCafeApplication  : The following 1 profile is active: "test"
2023-03-21T13:42:35.270-03:00 INFO 7652 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2023-03-21T13:42:35.270-03:00 INFO 7652 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2023-03-21T13:42:36.296-03:00 INFO 7652 ---[  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-03-21T13:42:36.422-03:00 INFO 7652 ---[  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 105 ms. Found 5 JPA repository interfaces.
2023-03-21T13:42:37.265-03:00 INFO 7652 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2023-03-21T13:42:37.286-03:00 INFO 7652 ---[  restartedMain] o.apache.catalina.core.StandardService   :  Starting service [Tomcat]
23-03-21T13:42:37.286-03:00 INFO 7652 --- [  restartedMain] o.apache.catalina.core.StandardEngine   :  Starting Servlet engine: [Apache Tomcat/10.1.5]
2023-03-21T13:42:37.395-03:00 INFO 7652 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]      Initializing Spring embedded WebApplicationContext
2023-03-21T13:42:37.396-03:00  INFO 7652 ---[  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2124 ms
2023-03-21T13:42:37.489-03:00 WARN 7652 ---[  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-21T13:42:37.493-03:00 INFO 7652 --- [  restartedMain] o.apache.catalina.core.StandardService  : Stopping service [Tomcat]
2023-03-21T13:42:37.529-03:00  INFO 7652 ---[  restartedMain]   .s.b.a.l.ConditionEvaluationReportLogger :

Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-03-21T13:42:37.568-03:00  ERROR 7652 ---[  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 (the profiles test are currently active).

Adicionei na minha classe "Application", a seguinte anotação:

@SpringBootApplication (exclude = {DataSourceAutoConfiguration.class }, scanBasePackages= {"com.minascafe.api.repositories"})

e parou de apresentar erro, mas não cria tabelas no banco MySql. (Lembrando que eu já criei o banco no MySql).

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

2023-03-21T14:33:17.466-03:00 INFO 8996 --- [  restartedMain]  com.minascafe.api.MinasCafeApplication   : Starting MinasCafeApplication using Java 17.0.6 with PID 8996 (C:\Users\Edson\OneDrive\Documentos\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasCafe\target\classes started by Edson in C:\Users\Edson\OneDrive\Documentos\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasCafe)
2023-03-21T14:33:17.481-03:00 INFO 8996 --- [  restartedMain]  com.minascafe.api.MinasCafeApplication   :  The following 1 profile is active: "test"
2023-03-21T14:33:17.577-03:00 INFO --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
 2023-03-21T14:33:17.578-03:00 INFO [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2023-03-21T14:33:19.294-03:00 INFO --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer :  Tomcat initialized with port(s): 8080 (http)
2023-03-21T14:33:19.311-03:00 INFO --- [  restartedMain] o.apache.catalina.core.StandardService  : Starting service [Tomcat]
2023-03-21T14:33:19.311-03:00 INFO --- [  restartedMain] o.apache.catalina.core.StandardEngine   : Starting Servlet engine: [Apache Tomcat/10.1.5]
2023-03-21T14:33:19.417-03:00 INFO --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]      : Initializing Spring embedded WebApplicationContext
2023-03-21T14:33:19.418-03:00 INFO --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1839 ms
2023-03-21T14:33:20.114-03:00 INFO --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer     : LiveReload server is running on port 35729
2023-03-21T14:33:20.196-03:00 INFO ---[  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-03-21T14:33:20.216-03:00 INFO --- [  restartedMain] com.minascafe.api.MinasCafeApplication  : Started MinasCafeApplication in 3.347 seconds (process running for 4.575)

A 2@ linha do console está informando que o profile de teste está ativo, mas eu não configurei profile de teste. Sinceramente não estou entendendo.

Alguém poderia me ajudar, por favor?!

Oi Edson!

Posta aqui o código da sua classe main MinasCafeApplication

package com.minascafe.api;
// @author Edson Ferreira Barbosa

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

//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"}) 
@EntityScan(basePackages = {"com.minascafe.api.entities"}) //Onde estão sendo criadas as classes Java mapeadas com @Entity


 public class MinasCafeApplication {

   public static void main(String[] args) {
        SpringApplication.run(MinasCafeApplication.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!");

       };        
        }*/

}

Deve ter alguma classe do teu projeto com a anotação @ActiveProfiles("test") ou nas configurações do Eclipse deve estar passando a variável de ambiente com o profile de test

Minhas classes de teste estão com essa anotação (@ActiveProfiles("test")). Mas essa anotação nas classes de teste deve influnciar na execução do projeto?

Ah, e detalhe, quando começou a apresentar essa situação eu deletei o profile de teste para ver o que aconteceria e mesmo assim apresenta esse erro.

package com.minascafe.api.repositories;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Date;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import com.minascafe.api.entities.Cafe_Coco;

@ExtendWith(SpringExtension.class)/*@RunWith(SpringRunner.class)*/ //diz ao JUnit para executar o teste usando a classe de execução do Spring Runner
@SpringBootTest
@ActiveProfiles("test")//ativando um profile do tipo 'Teste'

public class Cafe_CocoRepositoryTest {

    @Autowired //Diz ao Spring para injetar o Cafe_CocoRepository que foi criado antes para dentro do seu teste.
    private Cafe_CocoRepository cafe_cocorepository;

    private static int Lote = 215;

    @BeforeEach //executa esta operação antes da execução do join point
    public void setUp() /*Configurar*/ throws Exception {
        Cafe_Coco cafe_Coco = new Cafe_Coco();//Instancia a classe Cafe_Coco
        cafe_Coco.setProdutor("Humberto Bergamin");//Insere um nome de produtor  
        cafe_Coco.setLote(Lote);
        cafe_Coco.setData(new Date());
        cafe_Coco.setSacos(90);
        cafe_Coco.setQuilos(16.80);
        this.cafe_cocorepository.save(cafe_Coco);
    }

    @AfterEach //executa esta operação depois da execução do join point
    public final void tearDown()/*destruir*/{
        this.cafe_cocorepository.deleteAll(); //Deleta tudo
    }

    @Test //validando o teste
    public void testBuscarPorLote() {
        Cafe_Coco cafe_Coco = this.cafe_cocorepository.findByLote(Lote);

        assertEquals(Lote, Lote); //verifica se o lote declarado é o mesmo do Café em Côco retornado
    }

}

Árvore de arquivos do pacote de testes

Bom, em um ato de desespero (kkkkk!), deletei o projeto e recriei-o tal como estava. Parou de apresentar mensagem dizendo que estava ativo o profile de testes. Mas não está criando as tabelas no banco (MySql). Conforme mensionado acima, estava apresentando a seguinte mensagem no console:

***************************
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í, inseri a seguinte anotação em minha classe application: "@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})" e parou de apresentar mensagem de erro, mas não está criando as tabelas no banco de dados. Por ventura a inserção dessa anotação acima pode estar impedindo o acesso da aplicação ao banco?

Meu application properties atualizado:

#Configurações do JPA:
spring.datasource.url=jdbc:mysql://localhost:3306/minas_cafe?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=359423
spring.datasource.dbcp2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=validate


#Porta de trabalho do Tomcat
server.port=8080

#Exibe os comandos SQL
spring.jpa.show-sql=true

#Especifica qual o banco de dados você usará
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

#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.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!");

         };            
      }

}

Saída atual do console:


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

2023-03-24T08:39:13.634-03:00 INFO 116 ---  [  restartedMain]  com.cafe.api.MinasApplication           : Starting MinasApplication using Java 17.0.6 with PID 116 (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-24T08:39:13.653-03:00 INFO  116 ---  [  restartedMain]  com.cafe.api.MinasApplication           : No active profile set, falling back to 1 default profile: "default"
2023-03-24T08:39:13.735-03:00 INFO  116  ---  [  restartedMain]  .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2023-03-24T08:39:13.736-03:00  INFO 116 ---  [  restartedMain]  .e.DevToolsPropertyDefaultsPostProcessor  : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2023-03-24T08:39:15.209-03:00 INFO 116  ---  [  restartedMain]  o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2023-03-24T08:39:15.229-03:00 INFO 116  ---  [  restartedMain]  o.apache.catalina.core.StandardService  : Starting service [Tomcat]
2023-03-24T08:39:15.229-03:00 INFO 116  ---  [  restartedMain]  o.apache.catalina.core.StandardEngine   : Starting Servlet engine: [Apache Tomcat/10.1.5]
2023-03-24T08:39:15.341-03:00 INFO 116  ---  [  restartedMain]  o.a.c.c.C.[Tomcat].[localhost].[/]      :  Initializing Spring embedded WebApplicationContext
2023-03-24T08:39:15.341-03:00  INFO 116 ---  [  restartedMain] w.s.c.ServletWebServerApplicationContext Root WebApplicationContext: initialization completed in 1604 ms
2023-03-24T08:39:15.836-03:00  INFO 116 ---  [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer  :  LiveReload server is running on port 35729
2023-03-24T08:39:15.891-03:00  INFO 116 ---  [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-03-24T08:39:15.912-03:00 INFO 116  ---  [  restartedMain] com.cafe.api.MinasApplication           : Started MinasApplication in 2.889 seconds (process running for 3.878)
Executando o primeiro teste do projeto perfeitamente!
solução!

Edson, faz um teste, utiliza o IntelliJ no lugar do Eclipse para ver se o projeto funciona. Algumas pessoas tiveram esse mesmo erro e era problema no Eclipse.

Fui tentar abrir o projeto no Intellij, conforme sugerido, mas o Intellij não reconhece a estrutura de projeto do Eclipse sem alguns ajustes. Preferi criar um novo projeto com a estrutura criada pelo Intellij. De qualquer forma o Intellij não está reconhecendo algumas dependências do projeto. Como devo proceder?

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

Na aba do Maven, no canto direito da tela, clica no ícone de reload para o Maven tentar baixar as dependências:

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

Se não resolver, clica no ícone de Execute Maven Goal e rode o comando mvn clean -U:

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

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

Eu já havia clicado em "Reload All Maven Projects". Ao clicar em "Excecute Maven Goal" e executado o comando "mvn clean -u" gerou este erro:

"C:\Program Files\Java\jdk-17\bin\java.exe" -Dmaven.multiModuleProjectDirectory=C:\Users\Edson\Documents\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasIntellij -Djansi.passthrough=true "-Dmaven.home=C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.1\plugins\maven\lib\maven3" "-Dclassworlds.conf=C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.1\plugins\maven\lib\maven3\bin\m2.conf" "-Dmaven.ext.class.path=C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.1\plugins\maven\lib\maven-event-listener.jar" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.1\lib\idea_rt.jar=54961:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.1\plugins\maven\lib\maven3\boot\plexus-classworlds-2.6.0.jar;C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2023.1\plugins\maven\lib\maven3\boot\plexus-classworlds.license" org.codehaus.classworlds.Launcher -Didea.version=2023.1 clean -U
[INFO] Scanning for projects...
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-data-jpa:jar is missing. @ line 24, column 21
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-validation:jar is missing. @ line 34, column 21
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-web:jar is missing. @ line 38, column 21
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-devtools:jar is missing. @ line 43, column 21
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-test:jar is missing. @ line 55, column 21
 @ 
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]   
[ERROR]   The project org.example:MinasIntellij:1.0-SNAPSHOT (C:\Users\Edson\Documents\workspace-spring-tool-suite-4-4.17.2.RELEASE\MinasIntellij\pom.xml) has 5 errors
[ERROR]     'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-data-jpa:jar is missing. @ line 24, column 21
[ERROR]     'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-validation:jar is missing. @ line 34, column 21
[ERROR]     'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-web:jar is missing. @ line 38, column 21
[ERROR]     'dependencies.dependency.version' for org.springframework.boot:spring-boot-devtools:jar is missing. @ line 43, column 21
[ERROR]     'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-test:jar is missing. @ line 55, column 21
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException

Process finished with exit code 1

Me parece que está reclamando das versões das dependências.

Meu 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>MinasIntellij</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.6.15.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</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-parent</artifactId>
            <version>3.0.5</version>
            <type>pom</type>
        </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>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>

O problema é o pom.xml do seu projeto que está incorreto. Ele deveria estar assim:

<?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.5</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>org.example</groupId>
  <artifactId>MinasIntellij</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>MinasIntellij</name>
  <description>Demo project for Spring Boot</description>
  <properties>
    <java.version>17</java.version>
  </properties>
  <dependencies>
    <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>

Migrei meu projeto para o Intellij e alterei meu pom.xml conforme sugerido e funcionou perfeitamente. Executou sem erros e criou as tabelas no banco de dados (mysql). O Spring Tool Suite (Eclipse) me decepcionou! :|

Muito obrigado Otávio e Rodrigo! Vocês são fóda!