直接上代码以作笔记
一、对象集合
下述为对象集合的例子:
public class Info { @ApiModelProperty(value = "姓名") private String name; @ApiModelProperty(value = "性别") private String sex; @ApiModelProperty(value = "年龄") private Integer age; @ApiModelProperty(value = "爱好") private List<Hobby> list; } /** 此处为上面对象中的集合 */ public class Hobby { @ApiModelProperty(value = "爱好名称") private String name; @ApiModelProperty(value = "时长") private Integer duration; }
下述为xml中的代码:
<resultMap type="Info" id="map"> <result property="name" column="name" /> <result property="sex" column="sex" /> <result property="age" column="age" /> <!-- 这个就是对应对象中集合的内容 property(字段名) ofType(对象名) --> <collection property="list" ofType="Hobby"> <!-- 要是有主键的话就解除这个 --> <!-- <id property="id" column="id" /> --> <result property="name" column="name" /> <result property="duration" column="duration" /> </collection> </resultMap> <select id="query" resultMap="map"> SELECT user.name, user.sex, user.age, hobby.name, hobby.duration FROM t_user user <!-- 此处关联以作假设 --> LEFT JOIN t_hobby hobby ON hobby.user_id = user.id </select>
二、基本数据类型集合
基本数据类型的需要先用一个String类型来接受然后再方法体里用 ' , ' 分割一下遍历到集合中,这主要是因为所用到的GROUP_CONCAT函数是将查询到的数据用 ‘ , ’ 拼接并返回一个String类型
下述为基本数据类型对象集合的例子:
public class Info { @ApiModelProperty(value = "姓名") private String name; @ApiModelProperty(value = "性别") private String sex; @ApiModelProperty(value = "年龄") private Integer age; @ApiModelProperty(value = "爱好") private String hobby; @ApiModelProperty(value = "爱好集合") private List<String> hobbyList; }
下述为xml中的代码:
<resultMap type="Info" id="map">
<result property="name" column="name" />
<result property="sex" column="sex" />
<result property="age" column="age" />
<result property="hobby" column="hobby" />
</resultMap>
<select id="query" resultMap="map">
SELECT
user.name,
user.sex,
user.age,
<!-- GROUP_CONCAT作用是将数据以作逗号拼接返回的是一个String类型所以需要String来接收 -->
GROUP_CONCAT(hobby.name) as hobby
FROM t_user user
<!-- 此处关联以作假设 -->
LEFT JOIN t_hobby hobby ON hobby.user_id = user.id
</select>
若有更好的方案请在评论区分享一下,谢谢,学海无涯