前回SpringMVCで画面を表示するところまでやりました。
今回は、JdbcTemplateでDBにアクセスする部分を書いていきたいと思います。
postgresqlのインストール、設定
sudo apt-get install postgresql sudo su - sudo su - postgres psql postgres=# create database sample postgres=# \q createuser -P pguser (パスワードもpguserにした。スーパーユーザにしておく) exit exit
インストールと下準備(DBとユーザの作成)はこれでOK。
次に、postgreSQLにパスワードでログイン出来るように設定を変更する
sudo emacs -nw /etc/postgresql/8.4/main/pg_hba.conf
以下の部分を変更
#local all all ident # 修正前 local all all trust # 修正後
以下を実行してDBにログインできる事を確認する
psql sample -U pguser
ついでに今回のサンプルで使用するテーブルを定義しておく
sample=# create table sample_table (id bigint, name varchar(256), value float);
DBの準備はこれで完了。
beans-webmvc.xmlにDBを使用するための設定を追加する
今回はローカルのPostgreSQLを使用するけど、本番ではサーバ上のDBにアクセスするとか、PostgreSQLじゃなくてMySQLを使うことになったとかそういうときのために、どのRDBMSをつかうとか、ユーザ名とパスワードはどうだとかいう情報は別ファイルにしておいてあとから変更しやすいようにしておきます。
以下の内容のdatabase.propertiesをsrc/main/resources/に置きます。
jdbc.driverClassName=org.postgresql.Driver jdbc.url=jdbc:postgresql://localhost:5432/sample jdbc.username=pguser jdbc.username=pguser
このファイルを読み込むための設定をbeans-webmvc.xmlに追加します
<!-- DB用の設定ファイル --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="database.properties" /> </bean>
この設定を利用してDBアクセスするためのDriverManagerDataSourceを定義します。
<!-- DB接続用の設定 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean>
さらに、SQL文を渡して結果を受けとるためのJdbcTemplateも定義しておきます。
<!-- JDBC Template Bean --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean>
これでDBを使用するための設定は完了です
依存関係を追加する
上で追加したJdbcTemplateやPostgreSQLのドライバなどを使用するために以下のものを追加します。
pom.xmlをダブルクリックしてDependenciesタブをクリックします。
左側のAddを押して、以下の内容を記入してOKを押します。
Group Id: org.springframework Artifact Id: spring-jdbc Version: 3.1.1.RELEASE
Group Id: org.springframework Artifact Id: spring-test Version: 3.1.1.RELEASE
Group Id: postgresql Artifact Id: postgresql Version: 9.1-901.jdbc4
Group Id: javax.servlet Artifact Id: servlet-api Version: 2.5
これで依存性の追加は完了です。
DAOを定義する
データベースとやりとりするDAO(Data Access Object)を定義します。
今回はとりあえずテーブルに書き込む処理を行います。
package sample.dao; public interface SampleDao { public void insert(Long id, String name, Double value) ; }
package sample.dao.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import sample.dao.SampleDao; @Repository @Transactional public class SampleDaoImpl implements SampleDao{ @Autowired private JdbcTemplate jdbcTemplate; public void insert(Long id, String name, Double value) { jdbcTemplate.update("insert into sample_table (id, name, value) values (?, ?, ?);" , id, name, value); } }
単体テスト
ちゃんとDBにアクセスしてデータを書き込めるか確認するために単体テストを書きます。
package sample.dao; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/META-INF/spring/beans-webmvc.xml") public class SampleDaoImplTest { @Autowired SampleDao sampleDao; @Test public void insertTest() { assertThat(sampleDao, is(notNullValue())); sampleDao.insert(5L, "tarou", 1.4142); } }
エラー無く実行できたらDBに実際に書き込まれたか確認してみてください。
sample=# select * from sample_table; id | name | value ----+-------+-------- 5 | tarou | 1.4142 (1 行)
無事書き込めました。