Flex

BlazeDS + SpringFramework + MyBatis + HSQLDBの連携 / Annotation編

【 BlazeDS + SpringFramework + MyBatis + HSQLDBの連携 】



Spring Framework3.0.5 - DI(Dependency Injection)コンテナ
MyBatis3.0.6 - O/R Mapper
HSQLDB2.2.5 - Java製RDB



Spring2.0.x + iBatis2.x + HSQLDB1.8.xを Spring3.0.5 + MyBatis3.0.6 + HSQLDB2.2.5で置き換えてみました。
こちらはAnnotationベースでの実装となります。

DBのScirpt, FlexのMXML・ASは変わりませんので、XMLベースで実装したドキュメントを参考にして下さい。
MyBatisを使用して、Annotationベースの実装を2種類(Annotation指定のものと、 SelectBuilder/SqlBuilderを使用したもの)試してみました。
XML書かなくていいので、こちらの方が便利ではあるけれど、ソース追いかけるのがヤヤコシイかな?



[ web.xml ]
---
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <display-name>Spring BlazeDS</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>


    <!-- Filter config with GZIP -->
    <filter>
        <filter-name>CompressingFilter</filter-name>
        <filter-class>
            com.planetj.servlet.filter.compression.CompressingFilter
        </filter-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>statsEnabled</param-name>
            <param-value>false</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>CompressingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
   
    <servlet>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
        <init-param>
            <param-name>services.configuration.file</param-name>
            <param-value>/WEB-INF/flex/services-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet>
        <servlet-name>HttpContextUtilServlet</servlet-name>
        <servlet-class>com.chocbanana.http.HttpContextUtilServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>


    <servlet-mapping>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <url-pattern>/messagebroker/*</url-pattern>
    </servlet-mapping>
</web-app>
[ EOF ]
---

[ HttpContextUtilServlet.java ]
---
package com.chocbanana.http;

import java.io.Serializable;

import javax.servlet.ServletException;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


public class HttpContextUtilServlet extends javax.servlet.http.HttpServlet implements Serializable {

    private static WebApplicationContext ctx;
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        try{
            //dao.shutdown();
        }catch(Exception e){
            e.printStackTrace();
        }
        super.destroy();
    }

    @Override
    public synchronized void init() throws ServletException {
        // TODO Auto-generated method stub
        super.init();
        try{
            if(ctx == null) ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public synchronized static WebApplicationContext getContext(){
        return ctx;
    }
}
[ EOF ]
---



[ applicationContext.xml ]
---
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- jdbc.propertiesを認識させる propertyConfigurer -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>
                    classpath:/com/chocbanana/dao/database.properties
                </value>
            </list>
        </property>
    </bean>

    <!-- jdbc.propertiesの設定値をdataSourceにインジェクション -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${db.driver}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.user}" />
        <property name="password" value="${db.pass}" />
    </bean>

    <!-- Dao Mapperのサービスクラス・パッケージをコンポーネントスキャンだぜ! -->
    <context:component-scan base-package="com.chocbanana.dao.service"/>
     
    <!-- enable autowire -->
    <context:annotation-config />
   
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>
   
    <!-- トランザクション制御のインターセプターを構成 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
   
    <!-- 実装クラスのTransactionalアノテーションでジョイントポイントの認識をさせる  -->
    <!-- @transaction-managerのデフォルトは"transactionManager"だが念のため指定  -->
    <!-- @proxy-target-classをtureにしておく。CGLIBでプロキシーを作る方が多少速いらしい -->
    <!-- -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
   

    <!-- アノテーションベースのMapper -->
    <!--
     - コンポーネントスキャンでスキャンだぜ。Injectionされるだぜー。
     - MyBatisのDAO Mapperです。
    -->
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.chocbanana.dao.mapper" />
    </bean>
</beans>
[ EOF ]
---


[ database.properties ]
---
#Wed Apr 01 22:43:23 JST 2009
db.pass=
#db.url=jdbc\:hsqldb\:file:/Users/hoehoe/Documents/workspace/WEB-INF/resource/db
db.url=jdbc\:hsqldb\:file:C:/Documents and Settings/hoehoe/My Documents/EclipseProject/SpringBlazeDS/WEB-INF/resource/db
db.driver=org.hsqldb.jdbc.JDBCDriver
db.user=sa
[ EOF ]
---


[ DaoMapper.java ]
---
package com.chocbanana.dao.mapper;

import java.util.ArrayList;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.springframework.dao.DataAccessException;

import com.chocbanana.bean.PostMessage;

public interface DaoMapper {

    /* Annotation base */
    @Select("SELECT TOP 1000 * FROM MESSAGE ORDER BY ID DESC")
    ArrayList<PostMessage> getMessages() throws DataAccessException;

    @Insert("INSERT INTO MESSAGE (NAME, MAIL, MESSAGE, DAY) VALUES (#{name}, #{mail}, #{message}, #{day})")
    int putMessages(PostMessage Message) throws DataAccessException;
   
    /* SelectBuilder and SqlBuilder base  */
    @SelectProvider(type=com.chocbanana.dao.provider.SelectProvider.class, method="selectMessage")
    ArrayList<PostMessage> selectMessages() throws DataAccessException;
   
    @SelectProvider(type=com.chocbanana.dao.provider.SelectProvider.class, method="selectOne")
    PostMessage selectOne(PostMessage message) throws DataAccessException;

    @InsertProvider(type=com.chocbanana.dao.provider.SqlProvider.class, method="insertMessage")
    int insertMessages(PostMessage messge) throws DataAccessException;
   
}
[ EOF ]
---

[ SelectProvider.java ]
---
package com.chocbanana.dao.provider;

import static org.apache.ibatis.jdbc.SelectBuilder.BEGIN;
import static org.apache.ibatis.jdbc.SelectBuilder.FROM;
import static org.apache.ibatis.jdbc.SelectBuilder.SELECT;
import static org.apache.ibatis.jdbc.SelectBuilder.SQL;
import static org.apache.ibatis.jdbc.SelectBuilder.ORDER_BY;
import static org.apache.ibatis.jdbc.SelectBuilder.WHERE;

import com.chocbanana.bean.PostMessage;

public class SelectProvider {
     public static String selectMessage() {
         BEGIN();
         SELECT("TOP 1000 * ");
         FROM("MESSAGE");
         ORDER_BY("ID DESC");
         return SQL();
     }

     public static String selectOne(PostMessage message) {
         BEGIN();
         SELECT("*");
         FROM("MESSAGE");
         WHERE("ID like #{id}");
         return SQL();
     }
}
[ EOF ]
---


[ SqlProvider.java ]
---
package com.chocbanana.dao.provider;

import static org.apache.ibatis.jdbc.SelectBuilder.BEGIN;
import static org.apache.ibatis.jdbc.SqlBuilder.INSERT_INTO;
import static org.apache.ibatis.jdbc.SqlBuilder.VALUES;
import static org.apache.ibatis.jdbc.SqlBuilder.SQL;

import com.chocbanana.bean.PostMessage;

public class SqlProvider {
     public static String insertMessage(PostMessage message){
         BEGIN();
         INSERT_INTO("MESSAGE");
         VALUES("NAME, MAIL, MESSAGE, DAY", "#{name}, #{mail}, #{message}, #{day}");
         return SQL();
     }
}
[ EOF ]
---


[ FooService.java ]
---
package com.chocbanana.dao.service;

import java.util.ArrayList;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;

import com.chocbanana.bean.PostMessage;

@Transactional
public interface FooService {
    public ArrayList<PostMessage> getMessages() throws DataAccessException;
    public int putMessages(PostMessage Message) throws DataAccessException;
    public ArrayList<PostMessage> selectMessages() throws DataAccessException;
    public PostMessage selectOne(PostMessage message) throws DataAccessException;
    public int insertMessages(PostMessage messge) throws DataAccessException;
}

[ EOF ]
---

[ FooServiceImpl.java ]
---
package com.chocbanana.dao.service;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.chocbanana.bean.PostMessage;
import com.chocbanana.dao.mapper.DaoMapper;

@Service("fooService")
public class FooServiceImpl implements FooService {
   
    @Autowired
    private DaoMapper daoMapper;
   
    public void setDaoMapper(DaoMapper daoMapper){
        this.daoMapper = daoMapper;
    }
   
    public ArrayList<PostMessage> getMessages() throws DataAccessException{
        return this.daoMapper.getMessages();
    }
    public int putMessages(PostMessage Message) throws DataAccessException{
        return this.daoMapper.putMessages(Message);       
    }
    public ArrayList<PostMessage> selectMessages() throws DataAccessException{
        return this.daoMapper.selectMessages();
    }
    public PostMessage selectOne(PostMessage message) throws DataAccessException{
        return this.daoMapper.selectOne(message);
    }
    public int insertMessages(PostMessage messge) throws DataAccessException{
        return this.daoMapper.insertMessages(messge);
    }
}
[ EOF ]
---



[ FlexService.java ]
---
package com.chocbanana.ws;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.annotation.Resource;

import com.chocbanana.bean.*;
import com.chocbanana.dao.Db2DaoInterface;
import com.chocbanana.dao.service.FooService;
import com.chocbanana.http.HttpContextUtilServlet;

@SuppressWarnings("serial")
public class FlexService implements java.io.Serializable{

    @Resource
    private static FooService service;

    private static final String BEAN_TYPE="fooService";

    public FlexService(){
        service = (FooService) HttpContextUtilServlet.getContext().getBean(BEAN_TYPE);
    }
    public ArrayList<ResultMessage> getMessages(){
       
        ArrayList<ResultMessage> result = new ArrayList<ResultMessage>();
        try{
            ArrayList<PostMessage> list;
            list = service.selectMessages(); /* service.getMessages(); */

            java.util.Iterator<PostMessage> it = list.iterator();
            ResultMessage resultMsg = null;

            while(it.hasNext()){
                PostMessage _msg = it.next();
                resultMsg = new ResultMessage();
                resultMsg.setMessage(
                        _msg.getId() +  " " +
                        _msg.getName() + " " +
                        _msg.getMail() + " " +
                        _msg.getDay() + " " + "\n\n" +
                        _msg.getMessage());
                result.add(resultMsg);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
       
    }
    public int putMessages(PostMessage message) {
        int ret=0;
        String day = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        day = format.format(new java.util.Date());
        message.setDay(day);
       
        if("".equals(message.getMessage())){
            return 0;
        }
       
        try{
            ret = service.insertMessages(message); /* service.putMessages(message); */
        }catch(Exception e){
            e.printStackTrace();
        }
            return ret;
    }
}
[ EOF ]
---

このページの先頭へ