Open4

schema.sqlとは

miso_odenmiso_oden

何ができるか

schema.sqlを作成しておくことで、アプリケーション起動時にデータベースやテーブルを自動で作成することができる。
※ターミナルなどにデータベースやテーブルの情報を入力し作成する必要がない。

どこにどのようなタイトルのファイルを作るか

src/main/resources 直下に schema.sql を作成する

miso_odenmiso_oden

サンプルデータ

schema.sql

create schema if not exists `todo`;
use `todo`;
create table if not exists `todo_table` (
  `id` bigint(20) unsigned not null auto_increment comment 'ID',
  `title` varchar(30) not null comment 'タイトル',
  `created_at` datetime not null default current_timestamp comment '作成日時',
  `updated_at` datetime not null default current_timestamp on update current_timestamp comment '更新日時',
  primary key (`id`),
  unique key `title_unique` (`title`)
) engine=innodb default charset=utf8mb4 comment='todoテーブル';
miso_odenmiso_oden

サンプルデータ解説

todoというデータベースがない場合には同名でデータベースを作成する

create schema if not exists `todo`;

todoというデータベースを使用する

use `todo`;

todo_tableというデータベースがない場合には同名でデータベースを作成する

create table if not exists `todo_table` (
miso_odenmiso_oden

初期化の設定

application_proparties または application.ymlに、初期化が実行されるよう内容を記述する。

application_proparties

spring.sql.init.mode=always

application.yml

spring:  
  sql:
    init:
      mode: always