Spring MVC から Apache Derby を JPA経由で使用するアプリケーションを作成

 

あたりの作業をまとめて、SpringSource Tool Suite から、Spring MVC プロジェクトを作成し、Derbyのデモ用データに、JPA経由で接続していろいろ確認するためのアプリケーションを作成する。

 

Apache Derby のデモ用データから、Entity クラスを作成

Entity クラスを データベースからリバースで自動生成し、Spring MVC内で使いたいのだが、ちょっとやり方がわからないので、JPA プロジェクトを作成し、そのなかで Entityをリバースで作成(この手順ならできた) する。以下の手順に従い、JPAプロジェクトを作成する。

1.Spring Tool Suite でデータベースからエンティティクラスを作成する

JPA プロジェクトが作成できたら、Derby のデモ用のデータを利用できるようにする。

2.SpringSource Tool Suite から 組込DB apache Derby のデモ用データを利用する

ここで、再度、1.に戻って、データベースからEntityを作成する。

Spring MVC プロジェクトを作成し、Entity クラスを持ってくる

Spring MVC アプリケーションを以下に従い作成

SpringSource Tool Suite(STS) の導入~簡単なアプリケーションの作成

その後、上記で作成した、JPA プロジェクトから、生成された Entity クラスをコピーして持ってくる。

JPA用のライブラリなどは、以下を参照して、pom.xml に追記

Spring Tool Suite で Spring MVC から JPA(Java Persistence API) を利用する

永続化設定ファイル(persistence.xml)の記述

ここまでで、だいたい準備が整ったので、persistence.xml を作成する。

場所は、WEB-INF/classes/META-INF/persistence.xml

jdbc.user に app を指定しているのは、デモのサンプルテーブルが、app スキーマにあるから

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 
  xmlns="http://java.sun.com/xml/ns/persistence" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  
  <persistence-unit name="toursdb_persistence_unit" transaction-type="RESOURCE_LOCAL">
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        
    <class>info.typea.sampleweb.entity.Airline</class>
    <class>info.typea.sampleweb.entity.City</class>
    <class>info.typea.sampleweb.entity.Country</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>

    <properties>
      <property name="eclipselink.logging.level" value="FINEST"/> 
      <property name="eclipselink.target-database" value="Derby" />

      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
      <property name="javax.persistence.jdbc.url"  value="jdbc:derby:C:\Users\piroto\toursdb" />
      <property name="javax.persistence.jdbc.user" value="app" />
      <property name="javax.persistence.jdbc.password" value="" />
            
      <property name="eclipselink.ddl-generation" value="none" />
      <property name="eclipselink.ddl-generation.output-mode" value="database" />
    </properties>
  </persistence-unit>
</persistence>

処理の実装

DAO を 書く

Entity のデータを取得する DAO インターフェースと、実装クラスを作成

インターフェース

  • インターフェースにしなければいけないわけではないが、DIさせるための流儀に従う
package info.typea.sampleweb.dao;

import info.typea.sampleweb.entity.Airline;

import java.util.List;

public interface AirlineDao {
	public List<Airline> findAll();
}

実装クラス

  • createEntityManagerFactory の引数は、persistence.xml にしてした永続化ユニットの名称
  • createQuery のクエリは、SQLではなくて、JPQL from に続くのは、テーブル名ではなく、Entityクラス名
package info.typea.sampleweb.dao;

import info.typea.sampleweb.entity.Airline;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class AirlineDaoImpl implements AirlineDao {
    
    public List findAll() {
    
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("toursdb_persistence_unit");
        EntityManager em = emf.createEntityManager();

        @SuppressWarnings("unchecked")
        List list = em.createQuery("select o from Airline o").getResultList();
        
        return list;
    }
}

 

コントローラーを作成

  • Dao は、メンバーとして持っておき、アクセッサを用意。後ほどDIする
  • メソッドの引数にModel を用意しておき、名前に紐つけて結果オブジェクトをセット、後ほどJSPで利用する。
  • return は、"JSP" の名称、プレフィックス、サフィックスを付与し、指定された場所のJSPに遷移させる。servlet-context.xml にその指定がある
package info.typea.sampleweb.controller;

import info.typea.sampleweb.dao.AirlineDao;
import info.typea.sampleweb.entity.Airline;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 * @see http://static.springsource.org/spring/docs/3.1.0.M2/spring-framework-reference/html/mvc.html
 */
@Controller
public class FetchRecordsController {
    private static final Logger logger = LoggerFactory.getLogger(FetchRecordsController.class);

    private AirlineDao airlineDao;

    @RequestMapping(value="/fetch_records", method=RequestMethod.GET)
    public String fetchRecords(Model model) {
        logger.info("fetch records");
        
        List<Airline> airlines = this.airlineDao.findAll();
        model.addAttribute("airlines",airlines);
        
        return "fetch_records";
    }
    
    public AirlineDao getAirlineDao() {
        return airlineDao;
    }
    public void setAirlineDao(AirlineDao airlineDao) {
        this.airlineDao = airlineDao;
    }
}

JSPを作成

結果を表示するJSPを作成する

  • 上記でモデルにセットしたairlineを利用して画面を構築

fetch_records.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page session="false" %>
<html>
<head>
    <title>データを取得するサンプル</title>
</head>
<body>
<h1>
    データを取得するサンプル
</h1>

<table border="1">
    <tr>
        <th>AIRLINE_FULL</th>
        <th>BASIC_RATE</th>
        <th>DISTANCE_DISCOUNT</th>
        <th>BUSINESS_LEVEL_FACTOR</th>
        <th>FIRSTCLASS_LEVEL_FACTOR</th>
        <th>ECONOMY_SEATS</th>
        <th>BUSINESS_SEATS</th>
        <th>FIRSTCLASS_SEATS</th>
    </tr>
    <c:forEach items="${airlines}" var="airline">
        <tr>
            <td>${airline.airline}</td>
            <td>${airline.airlineFull}</td>
            <td>${airline.basicRate}</td>
            <td>${airline.businessLevelFactor}</td>
            <td>${airline.businessSeats}</td>
            <td>${airline.distanceDiscount}</td>
            <td>${airline.economySeats}</td>
            <td>${airline.firstclassSeats}</td>
        </tr>
    </c:forEach>
</table>

</body>
</html>

設定系

WEB-INF/spring/root-context.xml にDAOのBean定義

<bean id="airlineDao" class="info.typea.sampleweb.dao.AirlineDaoImpl"/>

WEB-INF/spring/appServlet/controllers.xml にコントローラーのBean定義

  • 上記で作成したDAOをDIする
<bean id="fetchRecordsControll" class="info.typea.sampleweb.controller.FetchRecordsController" >
    <property name="airlineDao" ref="airlineDao"/>
</bean> 

実行してみる

dataget01

見事表示されました。めでたしめでたし。

Follow me!

Spring MVC から Apache Derby を JPA経由で使用するアプリケーションを作成” に対して1件のコメントがあります。

  1. pppiroto (Hiroto YAGI) より:

    Derby の POM
    http://mvnrepository.com/artifact/org.apache.derby/derbyLocale_ja_JP/10.8.1.2
    org.apache.derby
    derbyLocale_ja_JP
    10.8.1.2

コメントを残す

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