原生jdbc方式:

Statement.getGeneratedKeys()

示例:

Statement stmt = null;
ResultSet rs = null; try { //
// Create a Statement instance that we can use for
// 'normal' result sets assuming you have a
// Connection 'conn' to a MySQL database already
// available stmt = conn.createStatement(); //
// Issue the DDL queries for the table for this example
// stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
stmt.executeUpdate(
"CREATE TABLE autoIncTutorial ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+ "dataField VARCHAR(64), PRIMARY KEY (priKey))"); //
// Insert one row that will generate an AUTO INCREMENT
// key in the 'priKey' field
// stmt.executeUpdate(
"INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')",
Statement.RETURN_GENERATED_KEYS); //
// Example of using Statement.getGeneratedKeys()
// to retrieve the value of an auto-increment
// value
// int autoIncKeyFromApi = -1; rs = stmt.getGeneratedKeys(); if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} else { // throw an exception from here
} System.out.println("Key returned from getGeneratedKeys():"
+ autoIncKeyFromApi);
} finally { if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
// ignore
}
} if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
// ignore
}
}
}

也有使用SELECT LAST_INSERT_ID() 注意:并发可能会出现问题。示例:

Statement stmt = null;
ResultSet rs = null; try { //
// Create a Statement instance that we can use for
// 'normal' result sets. stmt = conn.createStatement(); //
// Issue the DDL queries for the table for this example
// stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
stmt.executeUpdate(
"CREATE TABLE autoIncTutorial ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+ "dataField VARCHAR(64), PRIMARY KEY (priKey))"); //
// Insert one row that will generate an AUTO INCREMENT
// key in the 'priKey' field
// stmt.executeUpdate(
"INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')"); //
// Use the MySQL LAST_INSERT_ID()
// function to do the same thing as getGeneratedKeys()
// int autoIncKeyFromFunc = -1;
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()"); if (rs.next()) {
autoIncKeyFromFunc = rs.getInt(1);
} else {
// throw an exception from here
} System.out.println("Key returned from " +
"'SELECT LAST_INSERT_ID()': " +
autoIncKeyFromFunc); } finally { if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
// ignore
}
} if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
// ignore
}
}
}

mybatis封装后的配置如下:

<insert id="insert" parameterType="Post" useGeneratedKeys="true" keyProperty="id">

调用

postDao.add(post);

和以前一样结果后返回1,使用post.getId()可以获取到自增的id。

参考文献:

【1】http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-last-insert-id.html

【2】http://stackoverflow.com/questions/12241260/get-auto-genearated-key-for-the-inserted-record-in-mybatis

mysql 获取自增id的值的方法的更多相关文章

  1. MYSQL获取自增ID的四种方法

    MYSQL获取自增ID的四种方法 1. select max(id) from tablename 2.SELECT LAST_INSERT_ID() 函数 LAST_INSERT_ID 是与tabl ...

  2. DBS-MySQL:MYSQL获取自增ID的四种方法

    ylbtech-DBS-MySQL:MYSQL获取自增ID的四种方法 1.返回顶部 1. 1. select max(id) from tablename 2.SELECT LAST_INSERT_I ...

  3. MySQL中自增ID起始值修改方法

    在实际测试工作过程中,有时因为生产环境已有历史数据原因,需要测试环境数据id从某个值开始递增,此时,我们需要修改数据库中自增ID起始值,下面以MySQL为例: 表名:users; 建表时添加: ); ...

  4. YSQL获取自增ID的四种方法(转发)

    YSQL获取自增ID的四种方法(转发) 1. select max(id) from tablename 2.SELECT LAST_INSERT_ID() 函数 LAST_INSERT_ID 是与t ...

  5. MySQL自增ID 起始值 修改方法

    在mysql中很多朋友都认为字段为AUTO_INCREMENT类型自增ID值是无法修改,其实这样理解是错误的,下面介绍mysql自增ID的起始值修改与设置方法. 通常的设置自增字段的方法: 创建表格时 ...

  6. Entity Framework添加记录时获取自增ID值

    与Entity Framework相伴的日子痛并快乐着.今天和大家分享一下一个快乐,两个痛苦. 先说快乐的吧.Entity Framework在将数据插入数据库时,如果主键字段是自增标识列,会将该自增 ...

  7. [转] Entity Framework添加记录时获取自增ID值

    本文转自:http://blog.csdn.net/educast/article/details/8632806 与Entity Framework相伴的日子痛并快乐着.今天和大家分享一下一个快乐, ...

  8. mysql 数据库自增id 的总结

    有一个表StuInfo,里面只有两列 StuID,StuName其中StuID是int型,主键,自增列.现在我要插入数据,让他自动的向上增长,insert into StuInfo(StuID,Stu ...

  9. MyBatis映射文件1(增删改、insert获取自增主键值)

    增删改 Mybatis为我们提供了<insert>.<update>.<delete>标签来对应增删改操作 在接口中写增删改的抽象方法 void addEmp(Em ...

随机推荐

  1. tomcat安装部署

    1.tomcat6 下载地址 http://tomcat.apache.org/download-60.cgi 下载的话,下载那个.tar.gz后缀名的即可. 好像在 Linux.Unix上tomca ...

  2. OpenGL编程逐步深入(三)在窗口中显示一个三角形

    这一节教程的内容会比较少,我们仅仅是对上一节教程中的代码进行扩展,在窗口中渲染一个三角形出来. 本节我们以下图所示正方形来讲解OpenGl中的坐标系统.当沿着Z轴负方向看时,可见顶点的坐标必须在这个正 ...

  3. Python(十二) Pythonic与Python杂记

    一.导言 二.用字典映射代替switch case语句   # 字典代替 switch 语句 # switch () # { # case 0 : # dayName= 'a'; # break; # ...

  4. MYSQL去重复并计算总数的sql语句

    SELECT count(distinct uid) FROM `two_users`

  5. Android manifest文件中的标签详细介绍

    官方文档 概要 每一个Android应用都应该包含一个manifest文件,即AndroidManifest.xml.它包含了程序运行的一些必备信息,比如:--为Java应用程序指定一个独一无二的名字 ...

  6. win系统下的eclipse连接和使用linux上的hadoop集群

    准备工作 先在win系统的hosts文件中加入下面内容 10.61.6.164master     //hadoop集群的master节点 一.首先在eclipse上安装hadoop插件 下载hado ...

  7. VS NuGet使用

    通过这个可以自动联网下载内容! 很方便! 工具->NuGet包管理工具->程序包管理器控制台

  8. Linux下关机命令的区别 (halt,poweroff,reboot,shutdown,init)

    1.shutdown shutdown命令安全地将系统关机.    而在系统关机前使用shutdown命令﹐系统管理员会通知所有登录的用户系统将要关闭.并且login指令会被冻结﹐即新的用户不能再登录 ...

  9. area热点区域

    <area>标记:主要用于图像地图,通过该标记可以在图像地图中设定作用区域(又称为热点),这样当用户的鼠标移到指定的作用区域点击时,会自动链接到预先设定好的页面.其基本语法结构如下: &l ...

  10. Python 3 下载安装和环境搭建

    Python3 下载 由于博主使用的平台是Windows10,以下方法仅限win10系统 Python 官网:https://www.python.org/ 找到跟系统相应的版本瞎子: Python ...