需求:
筆者最近遇到一個需求:
- 一個團隊對應多個人,一個人只能有一個團隊
- 根據團隊的成績的降序,查詢出每個團隊的資訊,和其中每一個團隊中每個人的名字,
分析:
- 首先:需要查詢出每個人團隊的資訊
- 其次:查詢出每個團隊中對應的用戶的名字
- 所以回傳結果應該是
- 回傳一個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='人員表';
解決方案:
- sql
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://www.uj5u.com/qita/204021.html
標籤:其他
