2018年11月18日

Eclipse MyBatisの導入方法と使い方 その2

ここの記事からの続きです。

XMLにSQLのテンプレートを持たせることで、javaのソース改修や再ビルドなしにSQLの変更が可能になります。

ポイント
  • パターン1
    SQLの中で"<",">"記号を使う場合はエスケープする必要がある。
  • パターン2
    XMLにforeachを使うことで引数にListコレクションが渡せる
  • パターン3
    メソッドの戻り値をHashMapで受け取る。

UsertableMapper.javaに以下のメソッドを追加する。
    // UsertableMapper.java 既存のメソッドの下に追加

    /** 引数にDate型を渡す。 */
    List<Usertable> selectWhereDate(@Param("birthday") Date date);

    /** 引数にList渡す。 */
    List<Usertable> selectWhereList(@Param("addresslist") List<String> addresslist);

    /** 結果をMapで取得する。 */
    List<Map<String, Object>> selectGetMap();
mapperフォルダの下にVUsertableMapper.xml(UTF-8)を作成し、以下のように編集する。
<?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="jp.example.entity.dao.UsertableMapper">
 
  <!-- 引数にDate型を渡す。XML内で"<",">"記号を使うには、以下のように <![CDATA[ ? ]]> で囲みます。 -->
  <select id="selectWhereDate" parameterType="map" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from UserTable
    where birthday <![CDATA[ >= ]]> #{birthday,jdbcType=DATE}
    Order By userid
  </select>
 
  <!-- 引数にList渡す。 -->
  <select id="selectWhereList" parameterType="map" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from UserTable
    where (address IN
    <foreach item="item" collection="addresslist" open="(" separator="," close=")">
        #{item, jdbcType=VARCHAR}
    </foreach> )
    Order By userid
  </select>
 
  <!-- 結果をMapで取得する。 -->
  <select id="selectGetMap" parameterType="map" resultType="hashmap">
    select address as todofuken, count(address) as cnt
    from usertable
    group by address
    order by cnt
  </select>
</mapper>
mybatis-config.xmlに"VUsertableMapper.xml"の記述を追加する。

追加したメソッドの使用例
※サンプルなので引数が固定値になっていますが、実際は動的な値を渡します。
public class MyClass {
public static void main(String... args) {
try (Reader r = Resources.getResourceAsReader("mybatis-config.xml")) {
Properties properties = new Properties();

SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(r, properties);
try (SqlSession ss = ssf.openSession()) {
// Mapperインスタンス作成
UsertableMapper map = ss.getMapper(UsertableMapper.class);

// パターン1 日付を指定してレコード取得
// 条件:生年月日が1980年以降の人を取得
Date targetDate = (new SimpleDateFormat("yyyy/MM/dd")).parse("1980/01/01");
List<Usertable> result01 = map.selectWhereDate(targetDate);
System.out.println("パターン1");
for (Usertable cur : result01) {
System.out.println(cur.getName() + " - " + cur.getBirthday());
}

// パターン2 引数にListを渡す
List<String> nameList = new ArrayList<>();
nameList.addAll(Arrays.asList("奈良県", "大阪府"));
List<Usertable> result02 = map.selectWhereList(nameList);
System.out.println("パターン2");
for (Usertable cur : result02) {
System.out.println(cur.getName() + " - " + cur.getAddress());
}

// パターン3 結果をmapで取得
List<Map<String, Object>> result03 = map.selectGetMap();
System.out.println("パターン3");
for (Map<String, Object> cur : result03) {
System.out.println(cur.get("todofuken") + " - " + cur.get("cnt"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
タグ:JAVA Eclipse
posted by Hiro at 22:05| Comment(0) | プログラム