iBATIS2/iBATIS3/mybatis初期環境構築

環境構築、とは言っても簡単なDBテーブル作成〜単一行取得までですが。

個人的にiBATIS自体理解が深く無いのでiBATIS2については理解を深めるのと、iBATIS3/mybatis(ドキュメントを見る限り、今の所はほぼ同じ内容?)も併せて『同じテーマをどの様に実現出来るのか』辺りを焦点に学んでメモ出来て行ければ良いなぁと。



iBATIS2

こちらについては幸いにも日本語訳文書が存在するので、最初はこちらを参考に。

アクセス対象とするテーブルはPDF文書内の[PERSON]テーブルに。また、利用するDBは取り敢えずDerbyを用いる事に。

ライブラリはアーカイブからJARファイル[ibatis-2.3.4.726.jar]を入手、プロジェクトのクラスパスに追加。

DB環境整備後、以下のURLで接続。

ij version 10.6
ij> connect 'jdbc:derby://localhost:1527/ibatisDB;user=admin;password=admin;create=true';
ij>

テーブル作成。PDF文書内のCREATE TABLE文は以下の内容ですが、DB環境の違いでエラーとなる模様。

CREATE TABLE PERSON(
    PER_ID NUMBER (5, 0) NOT NULL,
    PER_FIRST_NAME VARCHAR (40) NOT NULL,
    PER_LAST_NAME VARCHAR (40) NOT NULL,
    PER_BIRTH_DATE DATETIME ,
    PER_WEIGHT_KG NUMBER (4, 2) NOT NULL,
    PER_HEIGHT_M NUMBER (4, 2) NOT NULL,
    PRIMARY KEY (PER_ID)
)

Derby対応という事で以下のCREATE TABLE文でテーブルを作成。

CREATE TABLE PERSON(
    PER_ID INTEGER NOT NULL,
    PER_FIRST_NAME VARCHAR (40) NOT NULL,
    PER_LAST_NAME VARCHAR (40) NOT NULL,
    PER_BIRTH_DATE DATETIME ,
    PER_WEIGHT_KG DECIMAL (4, 2) NOT NULL,
    PER_HEIGHT_M DECIMAL (4, 2) NOT NULL,
    PRIMARY KEY (PER_ID)
);

テーブルに対応したクラス(Person.java)。setter/getterは省略。

package examples.domain;

import java.util.Date;

public class Person {
    private int id;
    private String firstName;
    private String lastName;
    private Date birthDate;
    private double weightInKilograms;
    private double heightInMeters;
    :
    :    
    public String toString() {
        return "Person [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName
        + ", birthDate=" + birthDate + ", weightInKilograms=" + weightInKilograms + ", heightInMeters=" + heightInMeters + "]";
    }
}

テーブルに対応したxmlファイル(Person.xml)。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Person">

	<!--
		Use primitive wrapper type (e.g. Integer) as parameter and allow
		results to be auto-mapped results to Person object (JavaBean)
		properties
	-->
	<select id="getPerson" parameterClass="int" resultClass="examples.domain.Person">
		SELECT
		PER_ID as id,
		PER_FIRST_NAME as firstName,
		PER_LAST_NAME as lastName,
		PER_BIRTH_DATE as birthDate,
		PER_WEIGHT_KG as weightInKilograms,
		PER_HEIGHT_M as heightInMeters
		FROM PERSON
		WHERE PER_ID = #value#
	</select>
	<!--
		Use Person object (JavaBean) properties as parameters for insert. Each
		of the parameters in the #hash# symbols is a JavaBeans property.
	-->
	<insert id="insertPerson" parameterClass="examples.domain.Person">
		INSERT INTO
		PERSON (PER_ID, PER_FIRST_NAME, PER_LAST_NAME,
		PER_BIRTH_DATE, PER_WEIGHT_KG, PER_HEIGHT_M)
		VALUES (#id#, #firstName#, #lastName#,
		#birthDate#, #weightInKilograms#, #heightInMeters#)
	</insert>
	<!--
		Use Person object (JavaBean) properties as parameters for update. Each
		of the parameters in the #hash# symbols is a JavaBeans property.
	-->
	<update id="updatePerson" parameterClass="examples.domain.Person">
		UPDATE PERSON
		SET PER_FIRST_NAME = #firstName#,
		PER_LAST_NAME = #lastName#, PER_BIRTH_DATE = #birthDate#,
		PER_WEIGHT_KG = #weightInKilograms#,
		PER_HEIGHT_M = #heightInMeters#
		WHERE PER_ID = #id#
	</update>
	<!--
		Use Person object (JavaBean) “id” properties as parameters for delete.
		Each of the parameters in the #hash# symbols is a JavaBeans property.
	-->
	<delete id="deletePerson" parameterClass="examples.domain.Person">
		DELETE PERSON
		WHERE PER_ID = #id#
	</delete>

</sqlMap>

iBATIS用共通設定ファイル()。(SqlMapConfig.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <transactionManager type="JDBC">
        <dataSource type="SIMPLE">
            <property name="JDBC.Driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
            <property name="JDBC.ConnectionURL" value="jdbc:derby://localhost:1527/ibatisDB;user=admin;password=admin;create=true" />
            <property name="JDBC.Username" value="admin" />
            <property name="JDBC.Password" value="admin" />
        </dataSource>
    </transactionManager>

    <sqlMap resource="examples/sqlmap/maps/Person.xml" />

</sqlMapConfig>

ファイル構成。

└─src
    └─examples
        ├─domain
        │      Person.java
        │
        ├─exec
        │      InsertMain.java
        │      MyAppSqlConfig.java
        │      SelectMain.java
        │      UpdateMain.java
        │
        └─sqlmap
            └─maps
                    Person.xml
                    SqlMapConfig.xml

設定ファイル読み込み用のクラス(MyAppSqlConfig.java)

package examples.exec;

import java.io.Reader;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class MyAppSqlConfig {

    private static final SqlMapClient sqlMap;
    static {
        try {
            String resource = "examples/sqlmap/maps/sqlMapConfig.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
        } catch (Exception e) {
            // If you get an error at this point, it doesn’t matter what it was.
            // It is going to be unrecoverable and we will want the app to blow up hard so we are
            // aware of the problem. You should always log such errors and re-throw them in
            // such a way that you can be made immediately aware of the problem.
            e.printStackTrace();
            throw new RuntimeException("Error initializing MyAppSqlConfig class. Cause:" + e);
        }
    }

    public static SqlMapClient getSqlMapInstance() {
        return sqlMap;
    }
}

単一レコード取得のサンプル(SelectMain.java)。

package examples.exec;

import java.sql.SQLException;

import com.ibatis.sqlmap.client.SqlMapClient;

import examples.domain.Person;

public class SelectMain {
    public static void main(String[] args) throws SQLException {
        SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance(); // as coded above
        Integer personPk = new Integer(51);
        Person person = (Person) sqlMap.queryForObject ("getPerson", personPk);
        System.out.println(person);
    }
}

投入データ及び出力結果。

insert into PERSON values(51, '一朗','鈴木','1973-10-22',180.3,77.1);
----
Person [id=51, firstName=一朗, lastName=鈴木, birthDate=Mon Oct 22 00:00:00 JST 1973, weightInKilograms=180.3, heightInMeters=77.1]

iBATIS3

iBATIS2同様、公式サイトのPDF資料を参考に用意してみようと思ったのですが、肝心のテーブル構造情報(CREATE TABLE文)が資料内に見当たりません…。その他にもいまいち情報が追いづらい部分があるので、PDFを元に環境構築するのは一旦保留。

以下のサイトが一式揃っていそうだったので、これを参考に進めてみることに。

ライブラリはアーカイブからJARファイル[ibatis-3-core-3.0.0.220.jar]を入手、プロジェクトのクラスパスに追加。

以下ファイル諸々。パッケージ名を変更したり等若干修正が入ってます。

テーブルの作成。

CREATE TABLE automobiles (
    id INT NOT NULL,
    make VARCHAR(255) NOT NULL,
    model VARCHAR(255) NOT NULL,
    model_year INT NOT NULL
);

対応するクラス(Automobile.java)。例によってsetter/getterは省略。

package db.ibatis3.examples.model;

public class Automobile {
    private int id;
    private String make;
    private String model;
    private int year;

    public Automobile() {
        super();
    }
    :
    public Automobile(final int id, final String make, final String model,
        final int year) {

        super();
        this.id = id;
        this.make = make;
        this.model = model;
        this.year = year;
    }
    :
    @Override
    public String toString() {
        return "Automobile [id=" + id + ", make=" + make + ", model=" + model + ", year=" + year + "]";
    }
}

対象テーブルに対応するxmlファイル(automobile-mapper.xml)。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
    "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="db.mybatis.examples.model.Automobile">

    <resultMap type="Automobile" id="automobileResult">
        <result column="id" property="id" />
        <result column="make" property="make" />
        <result column="model" property="model" />
        <result column="model_year" property="year" />
    </resultMap>

    <select id="select" parameterType="int" resultType="Automobile" resultMap="automobileResult">
        select * from automobiles where id = #{id}
    </select>

    <insert id="insert" parameterType="Automobile">
        insert into automobiles (id, model, make, model_year)
        values (#{id}, #{model}, #{make}, #{year})
    </insert>

    <delete id="delete" parameterType="int">
        delete from automobiles where
	id = #{id}
    </delete>
  
    <delete id="deleteAll">
	delete from automobiles
    </delete>
</mapper>

iBATIS共通設定ファイル(mybatis-config.xml)。接続先DBはiBATIS2のものと同様。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias
        	type="db.mybatis.examples.model.Automobile"
            alias="Automobile" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
                <property name="url" value="jdbc:derby://localhost:1527/ibatisDB;user=admin;password=admin;create=true" />
				<property name="username" value="admin"/>
				<property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="db/mybatis/examples/model/automobile-mapper.xml" />
    </mappers>
</configuration>

ファイル構成。

└─src
    │  ibatis-config.xml
    │
    └─db
        └─ibatis3
            └─examples
                ├─exec
                │      SelectMain.java
                │
                └─model
                        automobile-mapper.xml
                        Automobile.java

単一レコード取得サンプル(SelectMain.java)。

package db.mybatis.examples.exec;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import db.mybatis.examples.model.Automobile;

public class SelectMain {
    public static void main(String[] args) throws IOException {
        Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
        SqlSession session = new SqlSessionFactoryBuilder().build(reader).openSession();
        Automobile automobile = (Automobile)session.selectOne("db.ibatis3.examples.model.Automobile.select", 1);
        System.out.println("#"+automobile);
    }
}

データ投入&実行結果。

insert into AUTOMOBILES VALUES(1,'make1','model1',2010);
----
Automobile [id=1, make=make1, model=model1, year=2010]

mybatis

基本的に、iBATIS3の内容をそのまま利用可能でした。念のためmybatisのXML定義に置き換えて実行。
ライブラリはアーカイブからJARファイル[mybatis-3.0.2.jar]を入手、プロジェクトのクラスパスに追加。

mybatis共通設定ファイル(mybatis-config.xml)。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias
        	type="db.mybatis.examples.model.Automobile"
            alias="Automobile" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
                <property name="url" value="jdbc:derby://localhost:1527/ibatisDB;user=admin;password=admin;create=true" />
				<property name="username" value="admin"/>
				<property name="password" value="admin"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="db/mybatis/examples/model/automobile-mapper.xml" />
    </mappers>
</configuration>

対象テーブル設定XMLファイル(automobile-mapper.xml)。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="db.mybatis.examples.model.Automobile">
	<resultMap type="Automobile" id="automobileResult">
		<result column="id" property="id" />
		<result column="make" property="make" />
		<result column="model" property="model" />
		<result column="model_year" property="year" />
	</resultMap>
	<select id="select" parameterType="int" resultType="Automobile"
		resultMap="automobileResult">
		select * from
		automobiles where id = #{id}
    </select>
	<insert id="insert" parameterType="Automobile">
		insert into automobiles (id,
		model, make, model_year)
		values (#{id}, #{model}, #{make}, #{year})
    </insert>
	<delete id="delete" parameterType="int">
		delete from automobiles where
		id = #{id}
  </delete>
	<delete id="deleteAll">
		delete from automobiles
  </delete>
</mapper>

便宜上パッケージ名等を若干変えましたが、基本iBATIS3の内容で動きそうな感じではあります。



以上、iBATIS2/iBATIS3/mybatisで初歩の初歩な部分を試してみました。…iBATIS3/mybatisはほぼ同じ内容のような気もするし、iBATIS自体既にmybatisに移行してしまっているので、学ぶ内容としてはiBATIS2系/mybatis系の2点で問題無さそうなのかな〜?

以後はテーマ毎に少しずつ学んで行ければと思います。