需求:
最近遇到一個需求:
一個團隊對應多個人,一個人只能有一個團隊
根據團隊的成績的降序,查詢出每個團隊的信息,和其中每一個團隊中每個人的名字。
分析:
首先:需要查詢出每個人團隊的信息
其次:查詢出每個團隊中對應的用戶的名字
所以返回結果應該是
返回一個List,List中每一個對象都是一個團隊,然后每一個團隊的人員名單顯示到List<String> userNames中。
數據庫表:(數據庫表只顯示了部分必要字段)
團隊表
CREATE TABLE `team` ( `id` varchar(255) NOT NULL COMMENT '雪花算法,id', `team_id` varchar(255) DEFAULT NULL COMMENT '團隊id', `team_name` varchar(255) DEFAULT NULL COMMENT '團隊名字', `group_results` float(8,2) DEFAULT NULL COMMENT '團隊成績' PRIMARY KEY (`id`) USING BTREE ) COMMENT='團隊表';
人員表
CREATE TABLE `person` ( `id` varchar(255) NOT NULL DEFAULT '' COMMENT '主鍵id(用戶id)', `team_id` varchar(22) DEFAULT NULL COMMENT '團隊id', `user_code` varchar(22) DEFAULT NULL COMMENT '學號', `user_name` varchar(22) DEFAULT NULL COMMENT '用戶姓名', PRIMARY KEY (`id`) USING BTREE ) COMMENT='人員表';
解決方案:
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
實體
構造的實體,很簡單,但是重要的一點就是返回的用戶名的集合
@Data public class TeamRanking { private String teamName;//小組名字 private Double teamGrade;//小組成績 private List<String> userNames; private Integer teamId; })
dao層
dao層返回的是上面那個對象的集合
List<TeamRanking> selectTeamRanking();
mybatis的mapper
在Mapper中,使用了ResultMap的collection標簽,並且:
collection的properties=對應名字的集合
collection標簽中result標簽的propertis內容也是對應集合的名字。
<select id="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> <resultMap id="selectTeamRankingMap" type="com.tfjybj.typing.model.TeamRankingModel"> <result property="teamId" column="team_id"></result> <result property="teamName" column="team_name"></result> <result property="teamGrade" column="group_results"></result> <collection property="userNames" ofType="string"> <result property="userNames" column="user_name"></result> </collection> </resultMap>
踩過的坑:
筆者也使用過,但是最后都沒有成功,最后在大家的討論中,嘗試出來上面的方式。
如果有大佬研究過mybaits的映射源碼的,筆者非常迫切的請求賜教。
<resultMap id="selectTeamRankingMap" type="com.tfjybj.typing.model.TeamRankingModel"> <result property="teamId" column="team_id"></result> <result property="teamName" column="team_name"></result> <result property="teamGrade" column="group_results"></result> <collection property="userNames" ofType="string" column="user_name"></collection> </resultMap>
<resultMap id="selectTeamRankingMap" type="com.tfjybj.typing.model.TeamRankingModel"> <result property="teamId" column="team_id"></result> <result property="teamName" column="team_name"></result> <result property="teamGrade" column="group_results"></result> <collection ofType="string" column="user_name"> <result property="userNames"></result> </collection> </resultMap>
轉:https://blog.csdn.net/qizhi666/article/details/109462142