mybatis foreach の index を使う

MyBatis の foreach の index を使えば、Multiple INSERT を実行するとき foreach のカウンタを挿入する行の
列の値にすることができる。

<insert id="insertEmployee" parameterType="map">
INSERT INTO employees ( employee_name , employee_no ) VALUES
<foreach collection="e_list" item="e"  separator="," index="index">
 ( #{e.dummy}, #{index} )
</foreach>
</insert>

これは、index="index" より #{index} が 0始まりで値が挿入される。0からでなく100から開始したければ、

<foreach collection="e_list" item="e"  separator="," index="index">
 ( #{e.dummy}, #{index} + 100 )
</foreach>

と書けば良い。

mybatis の SQLMap ステートメントとして、このように固定ではなく、foreach に渡すリストObject以外のものを
渡して foreach に書いて動的にすることもできる。

<foreach collection="e_list" item="e"  separator="," index="index">
 ( #{e.dummy}, #{index} + #{level} )
</foreach>

省略はするが、Map に渡して実行するサンプル

Map<String, Object> map = new HashMap<String, Object>();

map.put("e_list", employees_list);
map.put("level", 100);

SqlSession sesssion;

session.insert("org.sample.insertTest"), map);