PostgreSQL と Play Framwork を JDBC で連携接続する
環境
前提
- PlayFramework 初期状態から画面構築 に基づいて app 構築している
PostgreSQL 構築
(brew だと、createuser 上手くいかんかったんでこっちで... brew はまた別途...)
- Postgres.app 公式 の Quick Installation Guide の 1. 2. 3. 実行
- コマンドライン実行する為 PATH を ~/.bash_profile に設定する
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.4/bin
- app 用ロールと紐付く平文パスワードを設定
- ここではパスワードを testpass としておく
$ createuser testuser -d -P Enter password for new role: (input testpass) Enter it again: (again...)
- Superuser ロール で app 用ロールの DB を作成
$ psql matsukawa=# create database testuser;
- app 用ロール接続確認
$ psql -U testuser -W Password for user testuser: psql (9.4.4)
- app からの接続用 DB を作成
testuser=> create database dev_db;
Play から PostgreSQL 接続
build.sbt
- libraryDependencies を改修
- @ref-1
libraryDependencies ++= Seq( javaJdbc, // not jdbc but javaJdbc cache, javaWs, "org.postgresql" % "postgresql" % "9.4-1201-jdbc4" // change ver. by your postgresql ver @ref-2 )
conf/application.conf && ~/.bash_profile
- conf/application.conf > Database configuration を改修
- 秘匿情報を環境変数に逃がすのは個人的なシュミ
~/.bash_profile
- export 忘れないこと
- @ref-2
export PLAY_DEV_POSTGRES_URL="postgres://testuser:testpass@127.0.0.1/dev_db"
confi/application.conf
- driver のパッケージ名は
org.postgresql.Driver
- @ref-3
# Database configuration # ~~~~~ # You can declare as many datasources as you want. # By convention, the default datasource is named `default` # db.default.driver=org.postgresql.Driver db.default.url=${?PLAY_DEV_POSTGRES_URL}
app/controllers/Article.java
- 12 行目追加(RDBMS とコネクションを作る)
- /article/list に遷移して画面表示されるならば問題無し
- エラーが出るときは
- postgreSQL 接続先 host 変えてみる localhost <-> 127.0.0.1
- postgreSQL 起きてるか(default port 5432 が listen できるか) 確認する
./activator run
するコンソールでsource ~/.bash_profile
する
- エラーが出るときは
1 package controllers; 2 3 import play.*; 4 import play.mvc.*; 5 import views.html.*; 6 7 import play.db.DB; 8 import java.sql.Connection; 9 10 public class Article extends Controller { 11 public Result list() { 12 Connection con = DB.getConnection(); 13 return ok(views.html.article.list.render()); 14 } 15 }
参考
- @ref-1
- @ref-2
- @ref-3