需求:
笔者最近遇到一个需求:
- 一个团队对应多个人,一个人只能有一个团队
- 根据团队的成绩的降序,查询出每个团队的信息,和其中每一个团队中每个人的名字。
分析:
- 首先:需要查询出每个人团队的信息
- 其次:查询出每个团队中对应的用户的名字
- 所以返回结果应该是
- 返回一个List,List中每一个对象都是一个团队,然后每一个团队的人员名单显示到List<String> userNames中。
数据库表:(数据库表只显示了部分必要字段)
- 团队表
CREATETABLE`team`(`id`varchar(255)NOTNULLCOMMENT'雪花算法,id',`team_id`varchar(255)DEFAULTNULLCOMMENT'团队id',`team_name`varchar(255)DEFAULTNULLCOMMENT'团队名字',`group_results`float(8,2)DEFAULTNULLCOMMENT'团队成绩'PRIMARYKEY(`id`)USINGBTREE)COMMENT='团队表';
- 人员表
CREATETABLE`person`(`id`varchar(255)NOTNULLDEFAULT''COMMENT'主键id(用户id)',`team_id`varchar(22)DEFAULTNULLCOMMENT'团队id',`user_code`varchar(22)DEFAULTNULLCOMMENT'学号',`user_name`varchar(22)DEFAULTNULLCOMMENT'用户姓名',PRIMARYKEY(`id`)USINGBTREE)COMMENT='人员表';
解决方案:
- sql
SELECT
t.team_id,
t.team_name,
t.group_results,
p.`user_name`FROM`person` pRIGHTJOIN(SELECT t.team_id, t.team_name, t.group_resultsFROM`team` t) tON p.team_id= t.team_idORDERBY
group_resultsDESC
- 实体
- 构造的实体,很简单,但是重要的一点就是返回的用户名的集合
@DatapublicclassTeamRanking{privateString teamName;//小组名字privateDouble teamGrade;//小组成绩privateList<String> userNames;privateInteger teamId;})
- dao层
- dao层返回的是上面那个对象的集合
List<TeamRanking>selectTeamRanking();
- mybatis的mapper
- 在Mapper中,使用了ResultMap的collection标签,并且:
- collection的properties=对应名字的集合
- collection标签中result标签的propertis内容也是对应集合的名字。
<selectid="selectTeamRanking"resultMap="selectTeamRankingMap">
SELECT
t.team_id,
t.team_name,
t.group_results,
p.`user_name`
FROM
`person` p
RIGHT JOIN ( SELECT t.team_id, t.team_name, t.group_results FROM `team` t ) t ON p.team_id = t.team_id
ORDER BY
group_results DESC</select><resultMapid="selectTeamRankingMap"type="com.tfjybj.typing.model.TeamRankingModel"><resultproperty="teamId"column="team_id"></result><resultproperty="teamName"column="team_name"></result><resultproperty="teamGrade"column="group_results"></result><collectionproperty="userNames"ofType="string"><resultproperty="userNames"column="user_name"></result></collection></resultMap>
踩过的坑:
笔者也使用过,但是最后都没有成功,最后在大家的讨论中,尝试出来上面的方式。
如果有大佬研究过mybaits的映射源码的,笔者非常迫切的请求赐教。
<resultMapid="selectTeamRankingMap"type="com.tfjybj.typing.model.TeamRankingModel"><resultproperty="teamId"column="team_id"></result><resultproperty="teamName"column="team_name"></result><resultproperty="teamGrade"column="group_results"></result><collectionproperty="userNames"ofType="string"column="user_name"></collection></resultMap>
<resultMapid="selectTeamRankingMap"type="com.tfjybj.typing.model.TeamRankingModel"><resultproperty="teamId"column="team_id"></result><resultproperty="teamName"column="team_name"></result><resultproperty="teamGrade"column="group_results"></result><collectionofType="string"column="user_name"><resultproperty="userNames"></result></collection></resultMap>