MyBatis实现插入数据后得到主键以及collection标签的运用

插入数据后得到主键

    <insert id="insertComment" parameterType="com.zsy.domain.Comment"  useGeneratedKeys="true" keyProperty="id">
        insert into
            comment (uid, content, vid)
        values (#{userId}, #{content}, #{videoId})
    </insert>

不需要添加什么其它的配置,只需要在insert标签里面添加useGeneratedKeys="true" keyProperty="id",这里的keyProperty为自己定义的JavaBean的属性。
这里注意的是,上面的做法必须在设计表的时候指定主键自动增长,且主键唯一。同时参数必须为JavaBean,这样在插入成功之后作为参数的JavaBean的id会自动赋值为主键。


collection标签的运用

这里描述一下场景,实现一个评论功能,最终前端得到的数据除了评论的具体信息之外,还需要评论者的相关信息,如头像,昵称之类的,得到的效果如下:

如果只是使用普通的select语句加上collection标签,那么回复列表将得不到用户的信息,这个时候可以使用collection标签的selectcolumn属性,前者是查询语句,后者是查询的时候用到的参数,这样一来就可以把两个操作结合在一起,可以少写一些垃圾代码。下面贴一下项目中的部分代码:

resultMap

<!-- 评论对应一个resultMap-->
    <resultMap type="com.zsy.domain.Comment" id="commentResultMap">
        <id column="id" property="id"/>
               ........
        <!-- replyList为列表,这里注意不要指定ofType等属性,会冲突
        select指定为mapper中的方法
        -->
        <collection property="replyList"  select="com.zsy.mapper.CommentMapper.getReply"
        column="{commentId=id}">
        </collection>
    </resultMap>
    <!-- 回复对应一个resultMap-->
        <resultMap type="com.zsy.domain.Comment" id="replyResultMap">
        <id column="id" property="id"/>
        ........
    </resultMap>

mapper

    <select id="getComment" resultMap="commentResultMap">
        SELECT
        .....
        FROM
            comment AS c
            LEFT JOIN user ON user.id = c.id
        WHERE
        c.vid = #{videoId}
    </select>

    <select id="getReply" resultMap="replyResultMap">
        SELECT
        ......
        FROM
            reply AS r
            LEFT JOIN user ON user.id = r.id
        WHERE
            r.cid = #{commentId}
    </select>

mapper接口

@Repository
public interface CommentMapper {
    List<Comment> getComment(String videoId);
    List<Comment> getReply(Integer commentId);
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值