目录
在其对应的UserInfoMapper.xml里面写接口的实现sql.
场景
在我们的evalue表里有user_id这个字段,这个user_id就表示这个评价属于哪个用户,会存在多个评价属于同一个用户的情况,这里的用户就是一,评价就是多,它们一起构成可一对多的关系。
那么我们现在的需求就是在查询用户信息的时候,顺带查询出其所拥有的评价,这是一个非常典型的一对多查询。那么如何解决呢?
写Mybatis的查询接口
User实体新增一个evalueList属性,标注一下@TableField(exist = false)表示这个属性在数据库不存在,只是用来查询使用的。
在UserInfoMapper里面写一个接口
在其对应的UserInfoMapper.xml里面写接口的实现sql.
<select>标签里写上sql语句,在上面的<resultMap>标签里写结果的映射,<result>标签里 的property表示你的UserInfo实体类里的属性,column表示查询出来的sql里面的字段,注 意,sql字段可以取别名的,比如下面的e_id就是我取得别名。
为什么使用别名?这个别名很关键,我这里是简写,完整的写法前面加上as,比如 e.id as e_id,
在<resultMap>和<collection>标签里你可以指定type、ofType,来表示查询出的结果对应 的Java实体类的类型,这样结果映射就更清晰了。<collection>标签里的内容就是1对多里 面的多,也就是他会查出来一个List集合,对应到json里面就是数组。
还有一点你需要注意的是<collection>标签里的property必须跟你的User实体里定义的属性 名称一致,否则查询不出来任何结果。
<resultMap id="userMap" type="com.example.pipayshopapi.entity.UserInfo">
<result property="id" column="id"/>
<result property="uid" column="uid"/>
<result property="userName" column="user_name"/>
<result property="email" column="email"/>
<collection property="evaluateList" javaType="ArrayList" ofType="com.example.pipayshopapi.entity.ItemCommodityEvaluate">
<result property="id" column="e_id"/>
<result property="evaluate" column="e_evaluate"/>
<result property="createTime" column="e_create_time"/>
</collection>
</resultMap>
<select id="findUserEvaluate" resultMap="userMap">
select u.* , e.id e_id ,e.evaluate e_evaluate,e.create_time e_create_time from user_info u
left join item_commodity_evaluate e on u.uid=e.user_id
where u.uid=#{uid}
</select>