前提是:
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();
}
版权声明:本文为vah101原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。