SpringSource Tool Suite で Spring MVC から Spring JDBCを利用したコードを書く

 

基本的に、上記の本を参考にしつつ。

SpringSource Tool Suite(STS) の導入~簡単なアプリケーションの作成 で作成した、Spring MVC のスケルトンアプリに、Spring JDBC を利用したコードを組み込んでみる。

Java 標準の JDBC をそのまま使うと、以下の様な点が問題になる。

  • Connection,Statement,ResultSet インスタンスの管理などプログラミングが大変。
  • すべての例外がSQLExceptionであるため、例外処理が煩雑。
  • Connection インスタンスの取得の仕方がいろいろあり、環境により記述が変わる。

Spring JDBCを利用することで、

  • Connection のインスタンス管理を行ってくれる。
  • SQLException ではなく、汎用データベースアクセス例外が提供されているので、SQLStateを調べずに、例外の型による処理が可能。
  • Connection の取得は、DIにより一貫した取得方法が提供される。

ということになる。

Spring JDBC への参照設定

Spring Template Project - Spring MVC Project を作成すると、Spring JDBC への参照設定はなされていない。

Maven の設定ファイル、pom.xml の dependencies 要素に、Spring JDBC の記述を追加する。

spring_jdbc00

  1. <dependencies>
  2. <!-- JDBC -->
  3. <dependency>
  4. <groupid>org.springframework</groupid>
  5. <artifactid>spring-jdbc</artifactid>
  6. <version>3.0.0.RELEASE</version>
  7. <scope>compile</scope>
  8. </dependency>
  9. </dependencies>

 

JDBC ドライバの準備

準備した、DB2のサンプルデータベースに接続してみる。

https://www-304.ibm.com/support/docview.wss?rs=4020&uid=swg27016878

から、Driver for JDBC and SQLJ   をダウンロード、解凍すると、db2cc4.jar とうJDBCドライバがあるので、ダウンロード。

Mavenのローカルリポジトリに登録

ここを参考に、ローカルリポジトリにDB2 JDBC4 ドライバをインストールしてみる。

  1. mvn install:install-file -Dfile=<path-to-file>
  2. -DgroupId=<group-id>
  3. -DartifactId=<artifact-id>
  4. -Dversion=<version>
  5. -Dpackaging=<packaging>

設定値などは適当。適当なフォルダにJDBCドライバを置き、path-to-file に指定。mvnコマンド自体は、STSインストールにより、C:\springsource\maven-2.2.1.RELEASE\bin にインストールされていた。

実行。

  1. >C:\springsource\maven-2.2.1.RELEASE\bin>mvn install:install-file -Dfile=C:\Users\piroto\maven_local_lib\db2Jcc4.jar -Dgr
  2. oupId=db2jcc4 -DartifactId=db2Jcc4 -Dversion=9.7 -Dpackaging=jar -DlocalRepositoryPath=C:\Users\piroto\.m2\repository
  3. [INFO] Scanning for projects...
  4. [INFO] Searching repository for plugin with prefix: 'install'.
  5. [INFO] ------------------------------------------------------------------------
  6. [INFO] Building Maven Default Project
  7. [INFO] task-segment: [install:install-file] (aggregator-style)
  8. [INFO] ------------------------------------------------------------------------
  9. [INFO] [install:install-file {execution: default-cli}]
  10. [INFO] Installing C:\Users\piroto\maven_local_lib\db2Jcc4.jar to C:\Users\piroto\.m2\repository\db2jcc4\db2Jcc4\9.7\db2J
  11. cc4-9.7.jar
  12. [INFO] ------------------------------------------------------------------------
  13. [INFO] BUILD SUCCESSFUL
  14. [INFO] ------------------------------------------------------------------------
  15. [INFO] Total time: 3 seconds
  16. [INFO] Finished at: Thu May 19 22:38:44 JST 2011
  17. [INFO] Final Memory: 4M/109M
  18. [INFO] ------------------------------------------------------------------------

めでたくインストールできたので、Spring JDBC同様、pom.xml に追記。

  1. <dependency>
  2. <groupId>db2jcc4</groupId>
  3. <artifactId>db2jcc4</artifactId>
  4. <version>9.7</version>
  5. </dependency>

これでJDBCを使う準備は整った。

エンティティクラスの実装

  DB2のサンプルデータベースのSTAFFテーブルの定義を見ながら、Java のクラスを作成。

spring_jdbc01

  1. public class Staff {
  2. private Integer id;
  3. private String name;
  4. private Integer dept;
  5. private String job;
  6. private Integer years;
  7. private Double salary;
  8. private Double comm;
  9. @Override
  10. public String toString() {
  11. return String.format("%d,%s,%d,%s,%d,%f,%f",
  12. this.id,
  13. this.name,
  14. this.dept,
  15. this.job,
  16. this.years,
  17. this.salary,
  18. this.comm);
  19. }
  20. public Integer getId() {
  21. return id;
  22. }
  23. public void setId(Integer id) {
  24. this.id = id;
  25. }
  26. :
  27. }

DAOクラスの作成

Staff 取得用のインターフェース

  1. package info.typea.firstspringmvc.dao;
  2.  
  3. import java.util.List;
  4.  
  5. import org.springframework.dao.DataAccessException;
  6.  
  7. public interface StaffDao {
  8. List getStaffList() throws DataAccessException;
  9. }

Staff 取得の実装クラス

  1. package info.typea.firstspringmvc.dao;
  2.  
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.util.List;
  6.  
  7. import org.springframework.dao.DataAccessException;
  8. import org.springframework.jdbc.core.JdbcTemplate;
  9. import org.springframework.jdbc.core.RowMapper;
  10. import org.springframework.jdbc.core.support.JdbcDaoSupport;
  11.  
  12. public class StaffDaoImpl extends JdbcDaoSupport implements StaffDao {
  13.  
  14. @Override
  15. public List getStaffList() throws DataAccessException {
  16. RowMapper rowMapper = new StaffRowWraper();
  17. return getJdbcTemplate().query("SELECT * FROM staff", rowMapper);
  18. }
  19. protected class StaffRowWraper implements RowMapper {
  20. @Override
  21. public Staff mapRow(ResultSet result, int row) throws SQLException {
  22. Staff staff = new Staff();
  23. staff.setId(result.getInt("ID"));
  24. staff.setName(result.getString("NAME"));
  25. staff.setDept(result.getInt("DEPT"));
  26. staff.setJob(result.getString("JOB"));
  27. staff.setYears(result.getInt("YEARS"));
  28. staff.setSalary(result.getDouble("SALARY"));
  29. staff.setComm(result.getDouble("COMM"));
  30. return staff;
  31. }
  32. }
  33. }

依存性を注入

この状態で、いわゆるひとつの疎結合状態になっているので、設定ファイルで依存性をちゅーにゅーする。

実装クラスの基底クラス JdbcDaoSupport は、DataSource のセッターをもっていて、セットされたDataSource を元に、データベースに対する処理を行うようになっている。

root-context.xml の beans 要素の中に、dataSource を定義。ここに、JDBCの接続設定も記述しておく。

そして、DAOの実装クラスのdataSource プロパティに、上記で定義した、DataSourceを注入。

  1. <bean id="dataSource"
  2. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  3. <property name="driverClassName">
  4. <value>com.ibm.db2.jcc.DB2Driver</value>
  5. </property>
  6. <property name="url">
  7. <value>jdbc:db2://192.168.10.77:50000/sample</value>
  8. </property>
  9. <property name="username">
  10. <value>db2inst1</value>
  11. </property>
  12. <property name="password">
  13. <value>zzzzz</value>
  14. </property>
  15. </bean>
  16.  
  17. <bean id="staffDao"
  18. class="info.typea.firstspringmvc.dao.StaffDaoImpl">
  19. <property name="dataSource" ref="dataSource" />
  20. </bean>

コントローラに、DAOを注入

controllers.xml に、HomeController に 今作成したDAO を注入する記述をする。

sts_jdbc01

  1. <bean id="homeController"
  2. class="info.typea.firstspringmvc.controllers.HomeController">
  3. <property name="staffDao" ref="staffDao"/>
  4. </bean>

使ってみる

最初のサンプルアプリを作成した時のコントローラーで、ログを吐いている箇所を、データベースの結果を出力するように書き換える。

  1. package info.typea.firstspringmvc.controllers;
  2.  
  3. import info.typea.firstspringmvc.dao.Staff;
  4. import info.typea.firstspringmvc.dao.StaffDao;
  5.  
  6. import java.util.List;
  7.  
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10.  
  11. @Controller
  12. public class HomeController {
  13. private StaffDao staffDao;
  14. public void setStaffDao(StaffDao staffDao) {
  15. this.staffDao = staffDao;
  16. }
  17. @RequestMapping(value="/")
  18. public String home() {
  19. List stafflist = this.staffDao.getStaffList();
  20. for (Staff staff : stafflist) {
  21. System.out.println(staff.toString());
  22. }
  23. return "home";
  24. }
  25. }

実行

DB2を起動して、実行。

spring_jdbc03

取得できた!

いくつになっても、DBから値がとれてくるのはうれしいもんですね。

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です