0
1

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.

MyBatisでforeachを回す

Posted at

MyBatisでFormに含まれるメンバ変数のListをforeachに渡したい

MyBatisでforeachを回す際、@Paramで直接Listを渡して、そこから取り出す方法はよく見かけるのですが、Formを@Paramに渡してそのメンバ変数のlistをforeachで回したい時の方法がなかなか見つからなくて詰まりました。

実装

UserSearchForm.kt

data class (
    @Field:Positive
    @Field:Schema(
        required = false,
        type = "int",
    )
    val userId: Int? = null

    @Field:Positive
    @Field:Schema(
        required = false,
        type = "list",
    )
    val userTypeIds: List<Int>? = null
)
UserMapper.kt

@Mapper
interface UserMapper {
    @Select(
        """
            <script>
                SELECT user_id, user_name, email, user_type_id, created
                FROM users
                <where>
                    <if test="userSearchForm.userId != null">
                        user_id = #{userSearchForm.userId, jdbcType=INTEGER}
                    </if>
                    <if test="userSearchForm.userTypeIds != null">
                        AND user_status_id IN (
                            <foreach item="userTypeId" collection="userSearchForm.userTypeIds" open="(" separator="," close=")">
                                #{userTypeId}
                            </foreach>
                        )
                    </if>
                </where>
            </script>
        """)
    
}

躓いたところ

Mapperの引数に直接Listを渡して、その内容をforeachに渡すときであれば以下の通りcollection="list"で良いみたいなんですが、FormからListの値を取り出したい時は、collectionの方にlist型のメンバ変数を渡して(この場合userSearchForm.userTypeIds)、item#{}内にはその中身としてuserTypeIdを渡すようにしないと認識されないようです。

<foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
</foreach>

最初はこんな感じで書いていたのですが、これでやったところ

 <foreach item="userSearchForm.userTypeIds" collection="list" open="(" separator="," close=")">
     #{userSearchForm.userTypeIds}
</foreach>

以下のようなエラーになりました。

Parameter 'list' not found. Available parameters are [userSearchForm]

まあまずuserSearchForm.userTypeIdsの中身がlistなので、こちらはforeachの中身としてではなく、foreachさせる方のcollectionとして渡さなければいけなかったわけです。(当たり前と言えば当たり前だけど)

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?