0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

IteratorをSQLで使う

Posted at

SQLでiterateタグを使用したのでメモ

SQLの呼び出し

List<String> historyList = Arrays.asList("A", "B", "C");
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("historyList", historyList);

return (CompanyBean) this.getSqlMapClientTemplate().queryForObject("PowerSql.selectContractPlanInfo", paramMap);

SQLの実行

<select id="selectContractPlanInfo" parameterType="java.util.Map" resultMap="HistoryMap">
    SELECT
        SERVICE_CODE
    FROM
        WSC.TB_MST_PT_HISTORY
    <iterate prepend="WHERE" property="historyList" conjunction="OR">
        SERVICE_CODE = #historyList[]#
    </iterate>
</select>

解説

属性 説明
prepend SQL文に条件を追加する際の接頭辞を指定
property 繰り返し処理を行う対象のプロパティを指定
conjunction 各条件間の結合方法を指定します。ANDまたはORを指定することができる

iterateはMyBatisのタグの1つであり、繰り返し処理を行うために使用される。

    <!-- property=Mapのkey -->
    <iterate prepend="WHERE" property="historyList" conjunction="OR">
        SERVICE_CODE = #historyList[]#
    </iterate>

上記は以下のようなSQLを生成していることになる

WHERE 
    SERVICE_CODE = 'A'
    OR
    SERVICE_CODE = 'B'
    OR
    SERVICE_CODE = 'C'

iterateタグを使用することで、動的な条件生成と条件の結合方法の柔軟性が得られる。
もしiterateを使用しないとListに要素が追加された時、手動で条件文を書かなければならなくて柔軟性に欠ける。

//Dを追加
List<String> historyList = Arrays.asList("A", "B", "C","D",);
WHERE 
    SERVICE_CODE = 'A'
    OR
    SERVICE_CODE = 'B'
    OR
    SERVICE_CODE = 'C'
    OR
    SERVICE_CODE = 'D' <!-- 増えた分だけ追加する必要がある -->

終わり

動的にSQLを作成することができるので便利ですね:writing_hand:

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?