1. 程式人生 > 其它 >mybatis中返回一個List欄位

mybatis中返回一個List欄位

目的:在一個查詢接口裡面,返回一個人的資訊,以及這個人所攜帶的東西的資訊,返回效果如下:

{
  "msg": {
    "listMain": [
      {
        "id": "dd4a2f49b9c94196b065d425e1338ec4",
        "userName": "張三",
        "age": 24,
        "sex": "男",
        "list": [
          {
            "listid": "39f5d745751c97e4efadc7b92559",
            "mainId": "dd4a2f49b9c94196b065d425e1338ec4",
            "username": "張三的手機"
          },
          {
            "listid": "hvbhu515e751c97e4efadc7b92663",
            "mainId": "dd4a2f49b9c94196b065d425e1338ec4",
            "username": "張三的書包"
          }
        ]
      }
    ]
  }
}

實現方法:通過mybatis即可實現

<resultMap id="BaseResultMap" type="com.mihutao.pojo.userInfo">
<id column="id" jdbcType="VARCHAR" property="id"/>
<id column="userName" jdbcType="VARCHAR" property="user_name"/>
<id column="age" jdbcType="VARCHAR" property="age"/>
<id column="sex" jdbcType="VARCHAR" property="sex"/>
<collection property="flows" column="id"
ofType="com.mihutao.pojo.userThing"
select="com.mihutao.mapper.flowMapper.selectFlowById">
</collection>
//conllection這個標籤就是在返回值裡面引入list的方法
//其中flows是對應userInfo這個實體類的一個List欄位
//oftype指的是返回的內部list接收的實體類
//select指的是另一個xml裡面的查詢方法,將collection中column的id傳入到selectFlowById中
//總結就是將collection中column="id"傳入到selectFlowById中,返回值裝入ofType="com.mihutao.pojo.userThing"最後這一個list放入property="flows"這個欄位中
</resultMap>
<sql id="selectUserVo">
select id, user_name,age from user_info
</sql>

<select id="selectUserInfo" resultMap="BaseResultMap">
<include refid="selectUserVo"></include>
</select>

其中userInfo實體類中flows的寫法如下

private List<Flow> Flows = new ArrayList<>();