ページの先頭行へ戻る
Interstage Business Application Server オープンJavaフレームワークユーザーズガイド GlassFish編
FUJITSU Software

2.3.3 データアクセス

データアクセスについて説明します。

2.3.3.1 トランザクション制御

ORマッピング連携(Hibernate)ではHibernateTransactionManagerが使用可能です。

その他の機能ではSpring FrameworkではJTA(Java Transaction API)を利用してトランザクション制御を行うためのクラスが使用可能です。

Spring FrameworkのJtaTransactionManagerクラスでは、JTAのTransactionManagerインターフェースを利用して、以下に記載するEJBと同等のトランザクション属性をサポートしています。

2.3.3.2 Data Access Object(DAO)

DAOを使用することで、HibernateやJava Persistence API(JPA)などのデータベースアクセス機能を一貫した方法で処理できます。Spring Frameworkは以下のO/Rマッピング連携機能でDAOが使用できます。

2.3.3.3 JDBCにおけるデータアクセス

Spring FrameworkではJDBCを抽象化したフレームワークを提供しています。

JDBC APIを直接使用するより簡潔にデータアクセスコードを記述できるようになっています。

Spring Frameworkは以下の機能を提供します。

例外処理APIによって、アプリケーションは適切なSQLを発行し、その結果を抽出する事に専念する事が可能です。

また、Spring Framework固有のデータアクセス例外によって、JDBC特有のデータアクセス例外ではなくなるため、アプリケーションではthrowされる可能性があるすべてのJDBCデータアクセス例外を意識する必要がなくなります。

2.3.3.4 O/Rマッピング連携(Hibernate)

Hibernateと連携してO/Rマッピングできます。事前にJDBCデータソースを作成し、JNDIを使用して作成したJDBCデータソースに接続してください。

Hibernateを使用したO/RマッピングアプリケーションがJDBCデータソースに接続するためには、下記の設定が必要です。

  1. エンティティクラスの作成

  2. Bean定義ファイルの作成

  3. データベースアクセスクラスの作成

Hibernateを使用したO/RマッピングアプリケーションがJDBCデータソースに接続するための設定を以下に示します。

(1) エンティティクラスの作成

エンティティクラスを作成します。エンティティクラスにはEntityアノテーションを指定してください。

エンティティクラス:

package com.example.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table; @Entity @Table(name="test")
public class UserModel { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name="name") private String name; public void setName(String name) { this.name = name; } }

(2) Bean定義ファイルの作成

Spring FrameworkがHibernateに接続するために、Bean定義ファイルの設定が必要です。Bean定義ファイルの設定例を以下に示します。

Bean定義ファイル:

<?xml version="1.0" encoding="UTF-8"?>
…
    <!--- JNDIからデータソースを取得 -->
    <jee:jndi-lookup id="dataSource " jndi-name="testDB"/>

    <!--- セションファクトリの設定 -->
    <bean id="sessionFactory"
      class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!--- JNDIから取得したデータソースを指定 -->
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <!--- エンティティクラスを指定 -->
                <value>com.example.model.UserModel</value>
            </list>
        </property>
        <!--- Hibernateプロパティの設定 -->
        <property name="hibernateProperties">
            <props>
                <!--- データベースダイアレクトの設定 -->
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <!--- テーブルが存在しない場合は作成 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <!--- トランザクションマネージャの設定 -->
    <bean id="transactionManager"
      class="org.springframework.orm.hibernate5.HibernateTransactionManager" >
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
…

(3) データベースアクセスクラスの作成

データベースにアクセスするためのクラスを作成します。データベースアクセスクラスを作成する前に、DAOインターフェースを作成します。

Daoインターフェース:

package com.example.service;

import com.example.model.UserModel;

public interface UserDao { public void add(UserModel model); }

DAOインターフェースを実装して、データベースアクセスクラスを作成します。データベースにアクセスするために、セションファクトリを使用します。

データベースアクセスクラス:

package com.example.service;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.example.model.UserModel; @Repository
public class UserDaoImpl implements UserDao{ @Autowired
private SessionFactory sessionFactory; @Override public void add(UserModel model){ this.sessionFactory.getCurrentSession().persist(model); } }

2.3.3.5 O/Rマッピング連携(JPA)

JPAと連携してO/Rマッピングできます。事前にJDBCデータソースを作成し、JNDIを使用して作成したJDBCデータソースに接続してください。LocalContainerEntityManagerFactoryBeanを使用してEntityManagerFactory を設定してください。

JPAを使用したO/RマッピングアプリケーションがJDBCデータソースに接続するためには、下記の設定が必要です。

  1. エンティティクラスの作成

  2. 各種定義ファイルの作成

  3. データベースアクセスクラスの作成

注意

JPAの設定ファイルを本マニュアルではdeployment descriptor(persistence.xml)と表記しますが、Spring Frameworkのアプリケーションで使用する場合はファイル名をpersistence.xml以外にしてください。

JPAを使用したO/RマッピングアプリケーションがJDBCデータソースに接続するための設定を以下に示します。

(1) エンティティクラスの作成

エンティティクラスを作成します。エンティティクラスにはEntityアノテーションを指定してください。

エンティティクラス:

package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table; @Entity @Table(name="test")
public class UserModel { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name="name") private String name; public void setName(String name) { this.name = name; } }

(2) 各種定義ファイルの作成

Spring FrameworkがJPAに接続するには、下記のファイル設定が必要です。

  • Bean定義ファイル

  • deployment descriptor(persistence.xml)

Bean定義ファイルの設定例を以下に示します。

Bean定義ファイル:

<?xml version="1.0" encoding="UTF-8"?>
…
    <!--- LocalContainerEntityManagerFactoryBeanを使用-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <!--- deployment descriptorのファイル名と場所を指定 -->
        <property name="persistenceXmlLocation" value="classpath*:META-INF/my-persistence.xml" />
        <!--- データソースを指定 -->
        <property name="jtaDataSource" ref="dataSource" />
        <!--- エンティティマネージャの動作設定を指定 -->
        <property name="jpaPropertyMap">
            <map>
                <entry key="eclipselink.weaving" value="false"/>
                …
            </map>
        </property>
        <!--- JpaVendorAdapterを指定する -->
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
    </bean>
    <!--- JPAプロバイダアダプタを指定する -->
    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
        <!--- 接続先データベースに対応する値を指定 -->
        <property name="database" value="ORACLE"/>
    </bean>
    <!--- 接続先のJDBCリソースを指定 -->
    <jee:jndi-lookup id="dataSource" jndi-name="Test_DataSource"/>
    <!--- トランザクションマネージャの設定 -->
    <tx:jta-transaction-manager />
   
…

deployment descriptor(persistence.xml)の設定については、“Interstage Application Server GlassFish設計・構築・運用ガイド”の“JPAの提供機能”を参照してください。

deployment descriptor(persistence.xml):

<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <!--- ユニット名とトランザクション種別の指定 -->
    <persistence-unit name="testUnit" transaction-type="JTA">
        <exclude-unlisted-classes>false</exclude-unlisted-classes/>
        <properties>
            <!--- テーブルの自動生成 -->
            <property name="eclipselink.ddl-generation" value="create-tables" />
            …
        </properties>
    </persistence-unit>
</persistence>

(3) データベースアクセスクラスの作成

データベースにアクセスするためのクラスを作成します。データベースアクセスクラスを作成する前に、DAOインターフェースを作成します。

Daoインターフェース:

package com.example.service;

import com.example.model.UserModel;

public interface UserDao { public void add(UserModel userModel,String name); }

DAOインターフェースを実装して、データベースアクセスクラスを作成します。データベースにアクセスするために、セションファクトリを使用します。

データベースアクセスクラス:

package com.example.service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

import com.example.model.UserModel; @Repository
public class UserDaoImpl implements UserDao { @PersistenceContext private EntityManager em; @Override public void add(UserModel userModel,String name) { em.merge(userModel).setName(name); return userModel; } }

2.3.3.6 O/Rマッピング連携(MyBatis)

MyBatisと連携してO/Rマッピングできます。事前にJDBCデータソースを作成し、JNDIを使用して作成したJDBCデータソースに接続してください。

MyBatisを使用したO/RマッピングアプリケーションがJDBCデータソースに接続するためには、下記の設定が必要です。

  1. エンティティクラスの作成

  2. Bean定義ファイルの作成

  3. Mapperインターフェースの作成

  4. データベースアクセスクラスの作成

MyBatisを使用したO/RマッピングアプリケーションがJDBCデータソースに接続するための設定を以下に示します。

(1) エンティティクラスの作成

データを格納するためのJavaBeanであるエンティティクラスを作成してください。

エンティティクラス:

package com.example.model;

public class User { private int id; private String username; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }

(2) Bean定義ファイルの作成

O/RマッピングとしてMyBatisを使用するためにBean定義ファイルの設定が必要です。SqlSessionFactoryとMapperインターフェースを設定してください。

Bean定義ファイルの設定例を以下に示します。

Bean定義ファイル:

<?xml version="1.0" encoding="UTF-8"?>
…
    <!--- JNDIからデータソースを取得 -->
    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/mybatisAppDataSource"/>

    <!--- トランザクションマネージャの設定 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- SqlSessionFactoryの設定-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- MyBatisの設定 -->
        <property name="configuration">
            <bean class="org.apache.ibatis.session.Configuration">
                <property name="jdbcTypeForNull" value="OTHER"/>
            </bean>
        </property>
    </bean>

    <!-- Mapperインターフェースの取得-->
    <mybatis-spring:scan base-package="com.example.mapper" />
…

(3) Mapperインターフェースの作成

Mapperインターフェースにはオブジェクトを操作するためのSQL文の対応付けを記述してください。またSQL実行のメソッドを記述してください。

Mapperインターフェースの例を下記に示します。

SqlMapper.java:

package com.example.mapper;

import org.apache.ibatis.annotations.Insert; import com.example.model.User;
public interface SqlMapper { @Insert("INSERT INTO USERLIST (ID, USERNAME) VALUES (#{id}, #{username})") void addUser(User user); }

(4) データベースアクセスクラスの作成

データベースにアクセスするためのクラスを作成します。

Mapperインターフェースのオブジェクトをサービス層のオブジェクトに注入できます。

Spring Frameworkのトランザクションの中でMapperFactoryBeanがSqlSessionの生成とクローズを行うため、実行の処理を一行で記述できます。

SqlSessionはトランザクション終了時にコミット、またはロールバックされます。

インターフェース:

package com.example.service;

import com.example.model.User;

public interface UserService { public void add(User user); …

インターフェースを実装して、データベースアクセスクラスを作成してください。

データベースアクセスクラス:

package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.example.mapper.SqlMapper;
import com.example.model.User; @Service
public class UserServiceImpl implements UserService { @Autowired private SqlMapper sqlMapper; @Transactional public void add(User user) throws Exception { this.sqlMapper.addUser(user); } …

2.3.3.7 Object/XMLマッピング連携

JAXBと連携してJavaオブジェクトとXMLのマッピングができます。

Marshaller, Unmarshallerという2つのインターフェースを使用して変換をします。

Javaソース:

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller; …
public class Application { private static final String FILE_NAME = "settings.xml"; private Settings settings = new Settings(); private Marshaller marshaller; private Unmarshaller unmarshaller; … public void loadSettings() throws IOException { FileInputStream is = null; try { is = new FileInputStream(FILE_NAME); this.settings = (Settings) this.unmarshaller.unmarshal(new StreamSource(is)); } finally { if (is != null) { is.close(); } } } … }

Bean定義ファイル:

<oxm:jaxb2-marshaller id="jaxb2marshaller" contextPath="foo.bar.schema"/>
<bean id="application" class="Application">
    <property name="marshaller" ref="jaxb2marshaller" />
    <property name="unmarshaller" ref="jaxb2marshaller" />
</bean>