mybatis关联查询,先放结果图:
我想,分别查询几个表,然后通过java代码合并到一起应该也行,但是这里直接使用sql。
先定义 resultMap
<resultMap id="VideoDetailResultMap" type="com.xdclass.online_xd.domain.Video">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="title" jdbcType="VARCHAR" property="title"/>
<result column="summary" jdbcType="VARCHAR" property="summary"/>
<result column="cover_img" jdbcType="VARCHAR" property="coverImg"/>
<result column="price" jdbcType="INTEGER" property="price"/>
<result column="point" jdbcType="DOUBLE" property="point"/>
<result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
<collection property="chapterList" ofType="com.xdclass.online_xd.domain.Chapter">
<!-- <id column="id" jdbcType="INTEGER" property="id"></id>-->
<!--id重复不能成功映射,所以给下面id起个别名-->
<id column="chapter_id" jdbcType="INTEGER" property="id"/>
<result column="chapter_title" jdbcType="VARCHAR" property="title"/>
<result column="ordered" jdbcType="INTEGER" property="ordered"/>
<result column="chapter_create_time" jdbcType="TIMESTAMP" property="createTime"/>
<collection property="episodeList" ofType="com.xdclass.online_xd.domain.Episode">
<id column="episode_id" jdbcType="INTEGER" property="id"/>
<result column="num" jdbcType="INTEGER" property="num"/>
<result column="episode_title" jdbcType="VARCHAR" property="title"/>
<result column="episode_ordered" jdbcType="INTEGER" property="ordered"/>
<result column="play_url" jdbcType="VARCHAR" property="playUrl"/>
<result column="free" jdbcType="INTEGER" property="free"/>
<result column="episode_create_time" jdbcType="TIMESTAMP" property="createTime"/>
</collection>
</collection>
</resultMap>
然后使用
<select id="findDetailById" resultMap="VideoDetailResultMap">
SELECT v.id,
v.title,
v.summary,
v.cover_img,
v.price,
v.point,
v.create_time,
c.id AS chapter_id,
c.title as chapter_title,
c.ordered,
c.create_time as chapter_create_time,
e.id as episode_id,
e.num,
e.title as episode_title,
e.ordered as episode_ordered,
e.play_url,
e.free,
e.create_time as episode_create_time
FROM video v
LEFT JOIN
chapter c
ON
v.id = c.video_id
LEFT JOIN
episode e
ON
c.id = e.chapter_id
WHERE v.id = #{video_id}
ORDER BY c.ordered, e.num ASC
</select>
进行查询。
注意,column 不能重复,得起别名,
sql 记得起对应的别名
对应的Mapper
对应的实体类:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>