プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

SpringBoot入門 vol.6:データベースの準備をしよう

※今回はデータベースに「MySQL」を採用する
 
前提条件:PCにMySQLをインストールしておくこと
まだインストールしていない場合は下記を参照にインストールすること
 
MySQLのインストール方法
 
 


①「MySQL Driver」を設定する為、「build.gradle」に下記を記述

【記述するブロック】:dependencies

【記述するコード】:

runtimeOnly 'com.mysql:mysql-connector-j'

【記述例】:

dependencies {
    runtimeOnly 'com.mysql:mysql-connector-j'
}

 
 


②「Spring Data JPA」を設定する為、「build.gradle」に下記を記述

【記述するブロック】:dependencies

【記述するコード】:

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

【記述例】:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
}

 

上記までを反映した「build.gradle」の結果

plugins {
    id 'org.springframework.boot' version '2.2.1.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

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

repositories {
    mavenCentral()
}

configurations {
    developmentOnly
    runtimeClasspath {
        extendsFrom developmentOnly
    }
    compileOnly {
            extendsFrom annotationProcessor
    }
}

dependencies {
    runtimeOnly 'com.mysql:mysql-connector-j'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

test {
    useJUnitPlatform()
}

 
 


③src\main\resources\application.propertiesにDBの設定を記述

【記述例】

データベース名:springboot
ユーザー名:dbuser
パスワード:0000
 

# DB接続情報
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
# serverTimezone=JST はMySQL Connector/J 8.0.23から不要
# spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=JST
spring.datasource.username=dbuser
spring.datasource.password=0000
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

 
※注意点
下記記述は×
・spring.datasource.driverClassName=com.mysql.jdbc.Driver
⇒古いドライバークラスなので注意喚起が出る
 
 
前へ次へ
 
目次へ戻る