1、背景:
在向数据库插入数据时,在主键自增时不需要主键字段,但是接下来还需主键进行其它操作
2、实现:
实体类:
public class User {
private int userId;
private String username;
private String password;
private int age;
public User() {
}
public User(int userId, String username, String password, int age) {
this.userId = userId;
this.username = username;
this.password = password;
this.age = age;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
service层:
@Override
public int userAdd(User user) {
System.out.println("插入数据库之前的userId: " + user.getUserId());
int x = userMapper.userAdd(user);
System.out.println("插入数据库之后的userId: " + user.getUserId());
return x;
}
xml文件:
<insert id="userAdd" keyColumn="user_id"
useGeneratedKeys="true" keyProperty="userId">
insert into user (username,password) values(#{username},#{password})
</insert>
结果:
3、解释
useGeneratedKeys:
官方的说法是该参数的作用是:“允许JDBC支持自动生成主键,需要驱动兼容”
其本意是说:对于支持自动生成记录主键的数据库,如: MySQL , SQL Server ,此时设置useGeneratedKeys参数值为true,在执行添加记录之后可以获取到数据库自动生成的主键ID
keyProperty:
对应实体类中的字段
keyColumn:
对应数据库中的自增主键
标签:username,SpringBoot,回显,int,userId,主键,password,public From: https://www.cnblogs.com/MiaoStudy/p/17036117.html