这个需求就是一个对象里有多个类对象,比如有章节和小节,一个章节有多个小节,我们可以定义一个章节类,章节类里有一个小节类的集合,当前端循环遍历章节的同时可以在每个章节里遍历显示小节。
1.ChapterVo 章节类
package com.stu.eduservice.entity.chapter; import lombok.Data; import java.util.ArrayList; import java.util.List; @Data public class ChapterVo { private String id; private String title; //小节 private List<VideoVo> children = new ArrayList<>(); }
2.VideoVo小节类
package com.stu.eduservice.entity.chapter; import lombok.Data; @Data public class VideoVo { private String id; private String title; }
3.mapper接口
package com.stu.eduservice.mapper; import com.stu.eduservice.entity.EduChapter; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.stu.eduservice.entity.chapter.ChapterVo; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * <p> * 课程 Mapper 接口 * </p> * * @author stu * @since 2021-05-29 */ public interface EduChapterMapper extends BaseMapper<EduChapter> { List<ChapterVo> getChapterVideoByCourseId(String courseId); }
4.mapper.xml
- resultmap里的column要和sql里的列名一致(如果有别名要和别名一致)
- property要和类里的属性名一致,jdbcType要和数据库里字段定义的类型一致
- collection里的property要和实体类里的集合属性名称一致,ofType是类的包名加上类名路径
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.stu.eduservice.mapper.EduChapterMapper"> <resultMap id="BaseResultMap" type="com.stu.eduservice.entity.chapter.ChapterVo" > <id column="chapter_id" property="id" jdbcType="VARCHAR" /> <result column="chapter_title" property="title" jdbcType="VARCHAR" /> <collection property="children" ofType="com.stu.eduservice.entity.chapter.VideoVo"> <id column="video_id" property="id" jdbcType="VARCHAR" /> <result column="video_title" property="title" jdbcType="VARCHAR" /> </collection> </resultMap> <select id="getChapterVideoByCourseId" parameterType="java.lang.String" resultMap="BaseResultMap"> SELECT ec.id AS chapter_id, ec.title AS chapter_title, ev.id AS video_id, ev.title AS video_title FROM edu_chapter ec LEFT JOIN edu_video ev ON ev.chapter_id = ec.id WHERE ec.course_id = #{courseId} </select> </mapper>
5.前端遍历
<!-- 章节 --> <ul class="chanpterList"> <li v-for="chapter in chapterVideoList" :key="chapter.id"> <p> {{ chapter.title }} </p> <!-- 视频 --> <ul class="chanpterList videoList"> <li v-for="video in chapter.children" :key="video.id"> <p>{{ video.title }} </p> </li> </ul> </li> </ul>
效果截图