您现在的位置是:首页 > 电脑 > 

mybatis执行insert语句返回自增主键id值

2025-07-20 05:43:54
前提是: 1. 建表语句中指定了自增字段,如下: CREATE TABLE IF OT EXISTS `ttt`( `id` IT USIGED AUTO_ICREMET, `name` VARCHAR(100) OT ULL, PRIMARY KEY ( `id

前提是:

1. 建表语句中指定了自增字段,如下:

CREATE TABLE IF OT EXISTS `ttt`(
   `id` IT USIGED AUTO_ICREMET,
   `name` VARCHAR(100) OT ULL,
   PRIMARY KEY ( `id` )
)EGIE=InnoDB DEFAULT CHARSET=utf8;

2. 实体类StudentInfo中定义了setid方法:

public class StudentInfo {
	private Integer id;
    private String name ;
	private String class ;
	
	public void setId(Integer id) {
    	this.id = id;
    }
    
    public Integer getId() {
    	return id;
    }
    
	public void setame(String name) {
    	 = name;
    }
    
    public String getame() {
        return  name;
    }
	
	public void setClass(String class) {
    	 = class;
    }
    
    public String getClass() {
        return  class;
    }	
}

实现步骤:

1. 则在mapper.xml中,如下方式编写insert语句:

	    <insert id=insertStudent  useGeneratedKeys=true keyProperty=id  parameterType=com.StudentInfo>
        insert into ttt
        (name, class)
        VALUES
        (#{name, jdbcType=VARCHAR}, #{class, jdbcType=VARCHAR})
        )
        </insert> 

useGeneratedKeys设置使用自增主键

keyProperty=id指定类中的成员变量

4. 在serviceImpl类中调用:

StudentInfo stuInfo = new StudentInfo();
stuInfo.setame(张三);
stuInfo.setClass(法律一班);

try {
    studentMapper.insertStudent(stuInfo);
    Integer id = stuInfo.getId();
    println(插入成功,id为:  id);
}catch (Exception e) {
    e.printStackTrace();
} 

#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格

本文地址:http://www.dnpztj.cn/diannao/549540.html

相关标签:无
上传时间: 2023-06-29 02:07:04
留言与评论(共有 7 条评论)
本站网友 许智伟
17分钟前 发表
class) VALUES (#{name
本站网友 弹性座封闸阀
28分钟前 发表
PRIMARY KEY ( `id` ) )EGIE=InnoDB DEFAULT CHARSET=utf8; 2. 实体类StudentInfo中定义了setid方法: public class StudentInfo { private Integer id; private String name ; private String class ; public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } public void setame(String name) { = name; } public String getame() { return name; } public void setClass(String class) { = class; } public String getClass() { return class; } } 实现步骤: 1. 则在mapper.xml中,如下方式编写insert语句: <insert id=insertStudent useGeneratedKeys=true keyProperty=id parameterType=com.StudentInfo> insert into ttt (name
本站网友 石楠叶
3分钟前 发表
`name` VARCHAR(100) OT ULL
本站网友 r20
23分钟前 发表
jdbcType=VARCHAR}) ) </insert> useGeneratedKeys设置使用自增主键 keyProperty=id指定类中的成员变量 4. 在serviceImpl类中调用: StudentInfo stuInfo = new StudentInfo(); stuInfo.setame(张三); stuInfo.setClass(法律一班); try { studentMapper.insertStudent(stuInfo); Integer id = stuInfo.getId(); println(插入成功,id为:  id); }catch (Exception e) { e.printStackTrace(); }
本站网友 伤透心
4分钟前 发表
前提是: 1. 建表语句中指定了自增字段,如下: CREATE TABLE IF OT EXISTS `ttt`( `id` IT USIGED AUTO_ICREMET
本站网友 减肥吃什么
12分钟前 发表
jdbcType=VARCHAR}