获取刚刚 插入的自增主键

来源:互联网 发布:node.js 实战 第二版 编辑:程序博客网 时间:2024/05/22 13:07

一、插入记录

需求:新增一个博客记录
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
原创粉丝点击