Search code examples
javamysqlspringspring-boothibernate

Java Spring Boot creating a MySQL database at application startup


I am new in Java Spring. I created the default project by adding dependencies. Now I want the Weather database to be created when the application is launched, if it does not exist on the computer.I am using a mysql database.

How do I achieve this because I get errors when I launch the application?

and another question: is it possible to achieve that without explicitly specifying the username and password from the database?

java.sql.SQLSyntaxErrorException: Unknown database 'weather'
java.lang.NullPointerException: Cannot invoke "org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(java.sql.SQLException, String)" because the return value of "org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.sqlExceptionHelper()" is null

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.2.0'
    id 'io.spring.dependency-management' version '1.1.4'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
    sourceCompatibility = '17'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.mysql:mysql-connector-j'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/weather?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.sql.init.mode=always
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

Solution

  • A good idea could be to use Test containers. All you need to do is run docker. Springboot will handle the rest. It will automatically create and connect to the database without needing to know the username and password are. For my project I am using Postgres and the setup for MySql is the same. You will need to install the dependency for it.

    @TestConfiguration(proxyBeanMethods = false)
    public class TestContainersConfig {
    
        @Bean
        @ServiceConnection
        PostgreSQLContainer<?> postgreSQLContainer() {
            return new PostgreSQLContainer<>("postgres:15");
        }
    }
    

    I am using this for tests, so I run my application with a new database by doing the following:

    public class TestEchoBoardApplication {
    
    public static void main(String[] args) {
        SpringApplication.from(EchoBoardApplication::main)
                .with(TestContainersConfig.class)
                .run(args);
         }
    }