Mybatis映射
今天遇到一个需求,一张内容表content,一张用户表user,一张内容用户关联表(content_id,user_id),如果内容多用户可见的话,向关联表中写入多条数据。
现在的需求是内容表列表展示content的全部字段加上user集合字段,user类的话对应用户表的全部字段,写一条sql全部查出来。
首先,contentMapper.xml文件加入user表的map映射
<resultMap id="userMap" type="com.*.User">
<id property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
<result property="email" column="email"/>
</resultMap>
第二步,这个是你要查询的sql,这个地方因人而异。
我的需求是知道content_id,先去关联表中查出用户id集合,然后再在user表中查user集合
<select id="getUser" resultMap="userMap" resultType="java.lang.Long">
select *
from user
where user_id in (select user_id from user_content where content_id = #{id})
</select>
第三步,很关键,注意看倒数第二行是新加的;
在content映射中加入一个user,column是你调这个sql查询的入参(这里是content_id,也就是id),select指定要查的sql,也就是第二步新加的sql。
<resultMap type="com.insight.system.domain.SysAppContent" id="SysAppContentResult">
<id property="id" column="id"/>
<result property="title" column="title"/>
<result property="content" column="content"/>
<collection property="users" column="id" select="com.*.ContentMapper.getUser"/>
</resultMap>
最后,写接口执行查询语句,例如
select * from content;
得到结果