前提是:

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

CREATE TABLE IF NOT EXISTS `ttt`(
   `id` INT UNSIGNED AUTO_INCREMENT,
   `name` VARCHAR(100) NOT NULL,
   PRIMARY KEY ( `id` )
)ENGINE=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 setName(String name) {
    	this.name = name;
    }
    
    public String getName() {
        return  name;
    }
	
	public void setClass(String class) {
    	this.class = class;
    }
    
    public String getClass() {
        return  class;
    }	
}

实现步骤:

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

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

useGeneratedKeys设置使用自增主键

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

4. 在serviceImpl类中调用:

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

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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐