play 2.7.xのデータベース設定
データベースの設定を行った。
play 2.7.xだとあまり情報が転がってないので、過去バージョンの情報を見つつ試行錯誤した。
環境
OS:windows10
DB:postgreSQL 11.2
play: 2.7.2
postgreSQL jdbc:42.2.5
手順
1.PostgreSQLのダウンロード&インストール
ここは普通にインストールする。
ポートとパスワードは覚えておくこと。
www.enterprisedb.com
今回はローカルからの接続を想定して、pg_hba.confを編集しておく。
ローカルのユーザーは必要があれば追加しておく。
#ちなみに自分は勉強用なので、postgresで代用...。
# TYPE DATABASE USER ADDRESS METHOD # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust
2.application.confの編集
playのapplication.confを編集する。
# setting for postgresql db.default.driver=org.postgresql.Driver db.default.url="jdbc:postgresql://localhost:[port]/[database-name]" db.default.user=[username] db.default.password=[password] ebean.default="models.*"
1の方法をしておくと、db.default.userとdb.default.passwordの設定は必要なかった。
3.built.sbtの編集
以下を追加する。
libraryDependencies ++= Seq(evolutions, jdbc) libraryDependencies += "org.postgresql" % "postgresql" % "[JDBCのバージョン]" #現状の最新だと、[JDBCのバージョン]=42.2.5。
JDBCのバージョンはpostgreSQLだと以下から調べられる。
jdbc.postgresql.org
4.sqlファイルの作成
3までの設定ができている状態で、conf/evolutions/{database name}にsqlファイルがあれば、アプリ起動時にスキーマのevolutionが起こる。
今回は、defaultのデータベースを使うので、/conf/evolution/defaultにsqlファイルを設置する。
sqlファイルは例えばこんな感じ。
-- Users schema -- !Ups CREATE TABLE test (id serial not null, email varchar(255) not null, primary key (id)); -- !Downs DROP TABLE test;
特に、idはserial型にしているが、これはpostgreSQLのみ。
(当たり前だが、)MySQLはAUTO-INCREMENTなどなので、データベースに合わせてスキーマを作成すること。