DBに接続する(1/2)
DropWizardはDB接続用のライブラリとして、JDBIを採用している。(Hibernateも使えるらしいけど、私はあまり好きじゃないので・・)
で、前回設定ファイルを記述したが、そこにDBへの接続設定を記述すれば簡単にDBに接続できるようになっている。
シーケンス、テーブルを作成
まずは事前に以下のSQLを実行しておく。私の環境は PostgreSQL なので他のDBをお使いの場合はそれなりに修正してください。
CREATE SEQUENCE seq; CREATE TABLE sample ( id integer NOT NULL, name text NOT NULL, CONSTRAINT sample_pkey PRIMARY KEY (id) );
conf/dev.yml にDB接続設定を記述(PostgreSQLの例)
基本的には、user、password、urlをそれぞれの環境に合わせて変更するだけでOK
database: # the name of your JDBC driver driverClass: org.postgresql.Driver # the username user: usr (適当に書き換えてください) # the password password: ****** (適当に書き換えてください) # the JDBC URL url: jdbc:postgresql://192.168.52.128/dw (適当に書き換えてください) # any properties specific to your JDBC driver: properties: charSet: UTF-8 # the maximum amount of time to wait on an empty pool before throwing an exception maxWaitForConnection: 1s # the SQL query to run when validating a connection's liveness validationQuery: "/* MyService Health Check */ SELECT 1" # the timeout before a connection validation queries fail validationQueryTimeout: 3s # the minimum number of connections to keep open minSize: 8 # the maximum number of connections to keep open maxSize: 32 # whether or not idle connections should be validated checkConnectionWhileIdle: false # the amount of time to sleep between runs of the idle connection validation, abandoned cleaner and idle pool resizing evictionInterval: 10s # the minimum amount of time an connection must sit idle in the pool before it is eligible for eviction minIdleTime: 1 minute
JDBI、jdbcライブラリへの依存追加
pom.xml に以下の依存関係を追加。jdbc は自動的に解決してくれない(?)ので、手動で追加する。
<dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-jdbi</artifactId> <version>${dropwizard.version}</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.4-1201-jdbc41</version> </dependency>
ちょっと長くなるので、次に続く・・