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

Erro na migration

meu erro é o mesmo que do https://cursos.alura.com.br/forum/topico-falha-na-validacao-da-migration-no-momento-da-criacao-da-tabela-261742, porém ao executar o comando no MySQL e dá o seguinte erro:

2023-04-16T15:10:41.875-03:00  INFO 12864 --- [  restartedMain] med.voll.api.ApiApplication              : Starting ApiApplication using Java 20 with PID 12864 (C:\Users\thiag\Documents\curso\api\target\classes started by thiag in C:\Users\thiag\Documents\curso\api)
2023-04-16T15:10:41.880-03:00  INFO 12864 --- [  restartedMain] med.voll.api.ApiApplication              : No active profile set, falling back to 1 default profile: "default"
2023-04-16T15:10:41.993-03:00  INFO 12864 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2023-04-16T15:10:41.994-03:00  INFO 12864 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2023-04-16T15:10:43.661-03:00  INFO 12864 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2023-04-16T15:10:43.826-03:00  INFO 12864 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 144 ms. Found 2 JPA repository interfaces.
2023-04-16T15:10:45.559-03:00  INFO 12864 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2023-04-16T15:10:45.586-03:00  INFO 12864 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-04-16T15:10:45.586-03:00  INFO 12864 --- [  restartedMain] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.5]
2023-04-16T15:10:45.741-03:00  INFO 12864 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-04-16T15:10:45.745-03:00  INFO 12864 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3746 ms
2023-04-16T15:10:46.180-03:00  INFO 12864 --- [  restartedMain] o.f.c.internal.license.VersionPrinter    : Flyway Community Edition 9.5.1 by Redgate
2023-04-16T15:10:46.181-03:00  INFO 12864 --- [  restartedMain] o.f.c.internal.license.VersionPrinter    : See what's new here: https://flywaydb.org/documentation/learnmore/releaseNotes#9.5.1
2023-04-16T15:10:46.181-03:00  INFO 12864 --- [  restartedMain] o.f.c.internal.license.VersionPrinter    : 
2023-04-16T15:10:46.206-03:00  INFO 12864 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2023-04-16T15:10:47.052-03:00  INFO 12864 --- [  restartedMain] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@4d7e5daf
2023-04-16T15:10:47.057-03:00  INFO 12864 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2023-04-16T15:10:47.149-03:00  INFO 12864 --- [  restartedMain] o.f.c.i.database.base.BaseDatabaseType   : Database: jdbc:mysql://localhost/vollmed_api (MySQL 8.0)
2023-04-16T15:10:47.289-03:00  INFO 12864 --- [  restartedMain] o.f.core.internal.command.DbValidate     : Successfully validated 4 migrations (execution time 00:00.062s)
2023-04-16T15:10:47.332-03:00  INFO 12864 --- [  restartedMain] o.f.core.internal.command.DbMigrate      : Current version of schema `vollmed_api`: << Empty Schema >>
2023-04-16T15:10:47.371-03:00  INFO 12864 --- [  restartedMain] o.f.core.internal.command.DbMigrate      : Migrating schema `vollmed_api` to version "1 - create-table-medicos"
2023-04-16T15:10:47.421-03:00 ERROR 12864 --- [  restartedMain] o.f.core.internal.command.DbMigrate      : Migration of schema `vollmed_api` to version "1 - create-table-medicos" failed! Please restore backups and roll back database and code!
2023-04-16T15:10:47.472-03:00  WARN 12864 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Migration V1__create-table-medicos.sql failed
---------------------------------------------
SQL State  : 42S01
Error Code : 1050
Message    : Table 'medicos' already exists
Location   : db/migration/V1__create-table-medicos.sql (C:\Users\thiag\Documents\curso\api\target\classes\db\migration\V1__create-table-medicos.sql)
Line       : 1
Statement  : create table medicos(

Não coube o código todo.

2 respostas
solução!

Olá! Tudo bem? O erro está acontecendo porque essa tabela 'medicos' já existe na database que você está usando no seu projeto, para resolver esses problemas você tem algumas opções:

  • Trocar de database: Você pode começar uma database nova vazia e então trocar a URL do banco de dados no application.properties

Bastaria rodar um comando assim no seu terminal do MySQL:

CREATE DATABASE curso_spring_boot;

E então atualizar seu application.properties:

spring.datasource.url=jdbc:mysql://localhost:3306/curso_spring_boot?useTimezone=true&serverTimezone=America/Sao_Paulo
  • Trocar o comando SQL da migration: Como o erro está sendo causado porque a tabela que iria ser criada já existe, você pode usar o comando CREATE TABLE IF NOT EXISTS na migration, que não vai gerar erro se a tabela já existir.
CREATE TABLE IF NOT EXISTS medicos(
    id bigint not null auto_increment,
    nome varchar(100) not null,
    email varchar(100) not null unique,
    crm varchar(6) not null unique,
    especialidade varchar(100) not null,
    logradouro varchar(100) not null,
    bairro varchar(100) not null,
    cep varchar(9) not null,
    complemento varchar(100),
    numero varchar(20),
    uf char(2) not null,
    cidade varchar(100) not null,

    primary key(id)
);

Fazendo isso provavelmente vai ter algum problema relacionado as migrations do Flyway, então um jeito fácil de resolver seria excluir a tabela que o Flyway usa de histórico, o que não é muito indicado em projetos reais, mas nesse caso pode ser a solução:

USE nome_da_database;
DROP TABLE flyway_schema_history;

É importante lembrar de deixar o servidor da aplicação desligado quando estiver trabalhando com migrações e banco de dados para evitar erros, ligando só depois de ter arrumado o banco de dados e as migrações. Espero ter ajudado!

Obrigado!

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software