かんがるーさんの日記

最近自分が興味をもったものを調べた時の手順等を書いています。今は Spring Boot をいじっています。

Spring Boot で書籍の貸出状況確認・貸出申請する Web アプリケーションを作る ( その5 )( DB、テーブルの作成 )

概要

Spring Boot で書籍の貸出状況確認・貸出申請する Web アプリケーションを作る ( その4 )( Project の作成 ) の続きです。

  • 今回の手順で確認できるのは以下の内容です。
    • DB、テーブルの作成
    • Doma-Gen による entity, dao クラスの生成

参照したサイト・書籍

  1. Gradle 徹底入門

    Gradle徹底入門 次世代ビルドツールによる自動化基盤の構築

    Gradle徹底入門 次世代ビルドツールによる自動化基盤の構築

    • 「5.6 ファイル操作」を参照しました。

目次

  1. はじめに
  2. 1.0.x-create-database ブランチの作成
  3. ユーザとデータベースの作成
  4. テーブルの作成
  5. application.properties の変更
  6. Tomcat の起動、停止の確認
  7. Database tools の設定
  8. Doma-Gen による Entity クラス、Dao インターフェースの生成
  9. commit、Push、Pull Request、マージ

手順

はじめに

SQL ファイルを作成して PostgreSQL に DB とテーブルを作成します。

また Doma-Gen を利用して Entity クラス、Dao インターフェースを自動生成します。ksbysample-webapp-email の時は Dao インターフェースを自動生成した後、1ファイルずつ @ComponentAndAutowiredDomaConfig アノテーションを追加しましたが、今回は Gradle で付加してみます。

1.0.x-create-database ブランチの作成

  1. IntelliJ IDEA で 1.0.x-create-database ブランチを作成します。

ユーザとデータベースの作成

SQL ファイルを格納するための sql ディレクトリをプロジェクトのルート直下に作成します。

/sql の下に create_database.sql を作成します。作成後、リンク先の内容 に変更します。

コマンドプロンプトから以下のコマンドを実行してユーザとデータベースを作成します。

C:\project-springboot\ksbysample-webapp-lending\sql>psql -U postgres postgres
ユーザ postgres のパスワード:
psql (9.4.1)
"help" でヘルプを表示します.

postgres=# \i create_database.sql
CREATE ROLE
CREATE DATABASE
postgres=# \l
                                                  データベース一覧
    名前     |      所有者      | エンコーディング |      照合順序      | Ctype(
変換演算子)  |      アクセス権
-------------+------------------+------------------+--------------------+--------------------+-----------------------
 ksbyemail   | ksbyemail_user   | UTF8             | C                  | C
             |
 ksbylending | ksbylending_user | UTF8             | C                  | C
             |
 postgres    | postgres         | UTF8             | Japanese_Japan.932 | Japanese_Japan.932 |
 template0   | postgres         | UTF8             | Japanese_Japan.932 | Japanese_Japan.932 | =c/postgres          +
             |                  |                  |                    |
             | postgres=CTc/postgres
 template1   | postgres         | UTF8             | Japanese_Japan.932 | Japanese_Japan.932 | =c/postgres          +
             |                  |                  |                    |
             | postgres=CTc/postgres
(5 行)


postgres=# \q

C:\project-springboot\ksbysample-webapp-lending\sql>

テーブルの作成

/sql の下に create_table.sql を作成します。作成後、リンク先の内容 に変更します。

以下のテーブルレイアウトです。

ユーザテーブル ( user_info )

論理カラム名 物理カラム名 説明
ユーザID user_id
ユーザ名 username
パスワード password
メールアドレス mail_address
使用可否フラグ enabled

権限テーブル ( user_role )

論理カラム名 物理カラム名 説明
ユーザ権限ID role_id
ユーザID user_id
権限 role

貸出申請テーブル ( lending_app )

論理カラム名 物理カラム名 説明
貸出申請ID lending_app_id
申請状況 status 1:一時保存, 2:未申請, 3:申請中, 4:承認済
申請者ユーザID lending_user_id
承認者ユーザID approval_user_id

貸出申請書籍テーブル ( lending_book )

論理カラム名 物理カラム名 説明
貸出申請書籍ID lending_book_id
貸出申請ID lending_app_id
ISBN isbn
書籍名 book_name
貸出状況 lending_state 蔵書検索APIで取得した貸出状況の文字列がセットされる
貸出申請フラグ lending_app_flg 0:貸出申請しない, 1:貸出申請する
貸出申請理由 lending_app_reason
承認結果 approval_result 1:承認, 9:却下
承認理由 approval_reason

コマンドプロンプトから以下のコマンドを実行してテーブルを作成します。

C:\project-springboot\ksbysample-webapp-lending\sql>psql -U ksbylending_user ksbylending
ユーザ ksbylending_user のパスワード:
psql (9.4.1)
"help" でヘルプを表示します.

ksbylending=> \i create_table.sql
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
ksbylending=> \d
                             リレーションの一覧
 スキーマ |               名前               |     型     |      所有者
----------+----------------------------------+------------+------------------
 public   | lending_app                      | テーブル   | ksbylending_user
 public   | lending_app_lending_app_id_seq   | シーケンス | ksbylending_user
 public   | lending_book                     | テーブル   | ksbylending_user
 public   | lending_book_lending_book_id_seq | シーケンス | ksbylending_user
 public   | user_info                        | テーブル   | ksbylending_user
 public   | user_info_user_id_seq            | シーケンス | ksbylending_user
 public   | user_role                        | テーブル   | ksbylending_user
 public   | user_role_role_id_seq            | シーケンス | ksbylending_user
(8 行)


ksbylending=> \q

C:\project-springboot\ksbysample-webapp-lending\sql>

application.properties の変更

  1. src/main/resources の下の application-develop.properties, application-product.properties, application-unittest.properties を リンク先の内容 に変更します。

Tomcat の起動、停止の確認

  1. Gradle projects View から bootRun タスクを実行します。起動して "Started Application in ..." のログが出力されることを確認します。

  2. Ctrl+F2 を押して Tomcat を停止します。

Database tools の設定

  1. IntelliJ IDEA の画面右側に表示されている「Database」ボタンをクリックし、Database View を表示します。

  2. Database View の左上の「New」ボタンをクリックした後、「Data Source」->「PostgreSQL」メニューを選択します。

    f:id:ksby:20150704221151p:plain

  3. 「Data Sources and Drivers」ダイアログが表示されます。以下の値を入力します。

    • 「Database」に ksbylending を入力します。
    • 「User」に ksbylending_user を入力します。
    • 「Password」に xxxxxxxx を入力します。

    f:id:ksby:20150704221734p:plain

    入力後、「Test Connection」ボタンをクリックして以下のダイアログが表示されることを確認します。

    f:id:ksby:20150704222206p:plain

    確認後、「OK」ボタンをクリックしてダイアログを閉じます。

  4. Database View に ksbylending データベースのテーブルが表示されることを確認します。

    f:id:ksby:20150704222734p:plain

Doma-Gen による Entity クラス、Dao インターフェースの生成

  1. build.gradle を リンク先の内容 に変更します。

  2. Gradle projects View から gen タスクを実行し、Run View に "BUILD SUCCESSFUL" のログが出ることを確認します。

  3. src/main/java/ksbysample/webapp/lending の下に dao, entity パッケージが、src/main/resources の下に META-INF/ksbysample/webapp/lending/dao ディレクトリが自動生成されます。

    f:id:ksby:20150707003338p:plain

  4. 自動生成された Dao インターフェースを開くと、インターフェース名の上に @ComponentAndAutowiredDomaConfig が付加されています。

    f:id:ksby:20150707003529p:plain

commit、Push、Pull Request、マージ

  1. commit しようとしましたが、「Code Analysis」ダイアログが表示され「Review」ボタンをクリックすると大量の "SQL dialect is not configured." の Warning が出力されていました。修正します。

  2. どれでも構いませんのでログをダブルクリックして SQL ファイルを開きます。

  3. SQL ファイルが開くと上部に "SQL dialect is not configured." のメッセージが表示されていますので、メッセージの右側にある「Change dialect to ...」リンクをクリックします。

    f:id:ksby:20150707005248p:plain

  4. SQL Dialects」ダイアログが開きます。プロジェクトのルートで SQL Dialect を "PostgreSQL" に設定した後、「OK」ボタンをクリックします。

    f:id:ksby:20150707005639p:plain

  5. 再度 commit します。「Code Analysis」ダイアログが出ますが、他の Warning は無視して「Commit」ボタンをクリックします。

  6. GitHub へ Push、1.0.x-create-database -> 1.0.x へ Pull Request、1.0.x でマージ、1.0.x-create-database ブランチを削除、をします。

ソースコード

create_database.sql

CREATE USER ksbylending_user PASSWORD 'xxxxxxxx';
CREATE DATABASE ksbylending OWNER ksbylending_user TEMPLATE template0 ENCODING 'UTF8' LC_COLLATE 'C' LC_CTYPE 'C';

create_table.sql

create table user_info (
    user_id                 bigserial primary key
    , username              varchar(32) not null
    , password              varchar(32) not null
    , mail_address          varchar(256) not null
    , enabled               smallint not null default 1
);

create table user_role (
    role_id                 bigserial primary key
    , user_id               bigint not null references user(user_id) on delete cascade
    , role                  varchar(32) not null
);

create table lending_app (
    lending_app_id          bigserial primary key
    , status                varchar(1)
    , lending_user_id       bigint not null references user(user_id)
    , applicant_user_id     bigint not null references user(user_id)
);

create table lending_book (
    lending_book_id         bigserial primary key
    , lending_app_id        bigint not null references lending_app(lending_app_id) on delete cascade
    , isbn                  varchar(17) not null
    , book_name             varchar(128) not null
    , lending_app_flg       varchar(1)
    , lending_app_reason    varchar(128)
    , lending_state         varchar(16)
    , applicate_status      varchar(1)
    , applicate_reason      varchar(128)
);

application-develop.properties, application-product.properties, application-unittest.properties

■application-develop.properties

spring.datasource.url=jdbc:log4jdbc:postgresql://localhost/ksbylending
spring.datasource.username=ksbylending_user
spring.datasource.password=xxxxxxxx
spring.datasource.driverClassName=net.sf.log4jdbc.sql.jdbcapi.DriverSpy

spring.mail.host=localhost
spring.mail.port=25

spring.messages.cache-seconds=0
spring.thymeleaf.cache=false
spring.velocity.cache=false
  • spring.datasource.url, spring.datasource.username の値を上記のものに変更します。

■application-product.properties

server.tomcat.basedir=C:/webapps/ksbysample-webapp-lending

spring.datasource.url=jdbc:postgresql://localhost/ksbylending
spring.datasource.username=ksbylending_user
spring.datasource.password=xxxxxxxx
spring.datasource.driverClassName=org.postgresql.Driver

spring.mail.host=localhost
spring.mail.port=25

spring.thymeleaf.cache=true
  • spring.datasource.url, spring.datasource.username の値を上記のものに変更します。

■application-unittest.properties

spring.datasource.url=jdbc:postgresql://localhost/ksbylending
spring.datasource.username=ksbylending_user
spring.datasource.password=xxxxxxxx
spring.datasource.driverClassName=org.postgresql.Driver

spring.mail.host=localhost
spring.mail.port=25

spring.thymeleaf.cache=true
  • spring.datasource.url, spring.datasource.username の値を上記のものに変更します。

build.gradle

// for Doma-Gen
task gen << {
    def rootPackageName = 'ksbysample.webapp.lending'
    def daoPackagePath  = 'src/main/java/ksbysample/webapp/lending/dao'
    def workDirPath     = 'work'
    def workDaoDirPath  = "${workDirPath}/dao"
    
    // 現在の Dao インターフェースのバックアップを取得する
    delete "${workDirPath}"
    copy() {
        from "${daoPackagePath}"
        into "${workDaoDirPath}/org"
    }
    
    // Dao インターフェース、Entity クラスを生成する
    ant.taskdef(resource: 'domagentask.properties',
            classpath: configurations.domaGenRuntime.asPath)
    ant.gen(url: 'jdbc:postgresql://localhost/ksbylending'
                , user: 'ksbylending_user'
                , password: 'xxxxxxxx'
            ) {
        entityConfig(packageName: "${rootPackageName}.entity", useListener: false)
        daoConfig(packageName: "${rootPackageName}.dao")
        sqlConfig()
    }

    // 生成された Dao インターフェースを作業用ディレクトリにコピーし、
    // @ComponentAndAutowiredDomaConfig アノテーションを付加する
    copy() {
        from "${daoPackagePath}"
        into "${workDaoDirPath}/replace"
        filter {
            line -> line.replaceAll('import org.seasar.doma.Dao;', 'import ksbysample.webapp.lending.util.doma.ComponentAndAutowiredDomaConfig;\nimport org.seasar.doma.Dao;')
                        .replaceAll('@Dao', '@Dao\n@ComponentAndAutowiredDomaConfig')
        }
    }
    // @ComponentAndAutowiredDomaConfig アノテーションを付加した Dao インターフェースを
    // dao パッケージへ戻す
    copy() {
        from "${workDaoDirPath}/replace"
        into "${daoPackagePath}"
    }
    // 元々 dao パッケージ内にあったファイルを元に戻す
    copy() {
        from "${workDaoDirPath}/org"
        into "${daoPackagePath}"
    }
    // 作業用ディレクトリを削除する
    delete "${workDirPath}"
    
    // 自動生成したファイルを git add する
    def grgit = org.ajoberstar.grgit.Grgit.open(dir: project.projectDir)
    grgit.add(patterns: ['.'])
}
  • gen タスク内で、自動生成した Dao クラスに @ComponentAndAutowiredDomaConfig アノテーション を付加するようにしました。

履歴

2015/07/07
初版発行。
2015/10/25
* 貸出申請テーブル ( lending_app ) の申請状況/status の説明を "0:一時保存, 1:申請中, 2:承認済" → "1:一時保存, 2:未申請, 3:申請中, 4:承認済" へ変更しました。
2016/08/24
* ユーザテーブルのテーブル名を user と書いていた部分を user_info に修正しました。