获取刚刚 插入的自增主键

一、插入记录

需求:新增一个博客记录
mapper
    <insert id="insertBlog" parameterType="Blog">
        INSERT INTO `blog` (
          `title`,
          `author_id`,
          `state`,
          `featured`,
          `style`
        ) 
        VALUES
          (
            #{title},
            #{authorId},
            #{state},
            #{featured},
            #{style}
          )
    </insert>
接口:
int insertBlog(Blog blog);

测试:
    @Test
    public void testInsertBlog() {
        
        SqlSession session = MyBatisUtil.getSqlSession();
        BlogMapper blogMapper = session.getMapper(BlogMapper.class);
        
        Blog blog = new Blog();
        int count = blogMapper.insertBlog(blog);
        
        session.commit();
        session.close();
        
        System.out.println(blog);//看看是否有id值
        System.out.println("插入了" + count + "条记录");
    }

二、获取自增id

方式一:在mapper中配置  insert节点的属性  useGeneratedKeys = "true" keyProperty = "id"
mapper
    <insert id="insertBlog" parameterType="Blog" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO `blog` (
          `title`,
          `author_id`,
          `state`,
          `featured`,
          `style`
        ) 
        VALUES
          (
            #{title},
            #{authorId},
            #{state},
            #{featured},
            #{style}
          )
    </insert>

方式二: 在全局配置文件中配置 settings选项
    <settings>
        <setting name="useGeneratedKeys" value="true" />
    </settings>
并且在mapper的 insert 节点配置属性  keyProperty = "id"

方式三: 适用于没有自增主键的数据库
oracle版本
    <insert id="insertBlogOracle" parameterType="Blog">
        <selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id">
            select seq.nextval as id from dual
        </selectKey>
        INSERT INTO `blog` (
          `title`,
          `author_id`,
          `state`,
          `featured`,
          `style`
        ) 
        VALUES
          (
            #{title},
            #{authorId},
            #{state},
            #{featured},
            #{style}
          )    
    </insert>

mysql版本:
    <insert id="insertBlogMysql" parameterType="Blog">
        <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT INTO `blog` (
          `title`,
          `author_id`,
          `state`,
          `featured`,
          `style`
        ) 
        VALUES
          (
            #{title},
            #{authorId},
            #{state},
            #{featured},
            #{style}
          )    
    </insert>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值