Mybatis复杂数据结构新增和查询

复杂数据结构,嵌套foreach,新增数据,两次层List

 数据结构如下:

传参为Map<String, Object>,Object包含List(children),List中又包含List(list)

{
    "field01": "",
    "children": [
        {
            "field02": "",
            "list": [
                "",
                ""
            ]
        },
        {
            "field02": "",
            "list": [
            ]
        }
    ]
}

XML文件如下:

<insert id="insert" parameterType="java.util.Map">
     INSERT into table(field01, field02, field03) values
     <foreach collection="children" item="innerItem" separator=",">
         <choose>
             <when test="innerItem.list.size > 0">
                 <foreach collection="innerItem.list" index="index" item="item" separator=",">
                     (#{field01}, #{innerItem.field02}, #{innerItem.list[${index}]})
                 </foreach>
             </when>
             <when test="innerItem.list.size == 0">
                 (#{field01}, #{innerItem.field02}, NULL)
             </when>
         </choose>
     </foreach>
 </insert>

如果最内层是对象,取属性value对应的值,须对应修改:

#{innerItem.list[${index}]}
#{innerItem.list[${index}].value}

上述数据结构的 resultMap 如下:

<resultMap id="retMap" type="java.util.LinkedHashMap">
     <result column="field01" jdbcType="BIGINT" property="field01"/>
     <collection property="children" javaType="java.util.List" ofType="java.util.LinkedHashMap">
         <result column="field02" jdbcType="VARCHAR" property="field02"/>
         <collection property="list" javaType="java.util.List" ofType="java.lang.Object">
             <result column="value" jdbcType="VARCHAR" property="value"/>
         </collection>
     </collection>
 </resultMap>

相关推荐