美文网首页
Mybatis 插入数据时获取自增主键

Mybatis 插入数据时获取自增主键

作者: tingshuo123 | 来源:发表于2018-07-12 16:23 被阅读3次

    Mapper.xml 配置

    在插入标签中添加 useGeneratedKeys="true"keyProperty="id" 属性就可以了,Mybatis 会将自动增长的 id 填入,作为输入参数传入的实体Bean中。

    <mapper namespace="book">
        <insert id="insertBook" parameterType="bean.BookBean" useGeneratedKeys="true" keyProperty="id">
            INSERT INTO t_book(`name`) VALUE(#{name});
        </insert>
    </mapper>
    

    代码

    public void insertBook(BookBean bean) {
            
            SqlSession session = MybaitsUtil.getSqlSession(true);
            try {
                session.insert("book.insertBook", bean);
                // id 会自动填入 bean 中
                System.out.println("自增长id为:" + bean.getId());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                session.close();
            }
        }
    

    相关文章

      网友评论

          本文标题:Mybatis 插入数据时获取自增主键

          本文链接:https://www.haomeiwen.com/subject/hejrpftx.html