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

 

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

 数据结构如下:

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

 1 {
 2     "field01": "",
 3     "children": [
 4         {
 5             "field02": "",
 6             "list": [
 7                 "",
 8                 ""
 9             ]
10         },
11         {
12             "field02": "",
13             "list": [
14             ]
15         }
16     ]
17 }

 

XML文件如下:

 1  <insert id="insert" parameterType="java.util.Map">
 2      INSERT into table(field01, field02, field03) values
 3      <foreach collection="children" item="innerItem" separator=",">
 4          <choose>
 5              <when test="innerItem.list.size > 0">
 6                  <foreach collection="innerItem.list" index="index" item="item" separator=",">
 7                      (#{field01}, #{innerItem.field02}, #{innerItem.list[${index}]})
 8                  </foreach>
 9              </when>
10              <when test="innerItem.list.size == 0">
11                  (#{field01}, #{innerItem.field02}, NULL)
12              </when>
13          </choose>
14      </foreach>
15  </insert>

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

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

上述数据结构的 resultMap 如下:

1  <resultMap id="retMap" type="java.util.LinkedHashMap">
2      <result column="field01" jdbcType="BIGINT" property="field01"/>
3      <collection property="children" javaType="java.util.List" ofType="java.util.LinkedHashMap">
4          <result column="field02" jdbcType="VARCHAR" property="field02"/>
5          <collection property="list" javaType="java.util.List" ofType="java.lang.Object">
6              <result column="value" jdbcType="VARCHAR" property="value"/>
7          </collection>
8      </collection>
9  </resultMap>

 

posted on 2020-04-20 15:11  blouson  阅读(494)  评论(0编辑  收藏  举报