mybatis 返回主键
对应pojo
@ApiModel("用户数据模型")
public class UserModel {
@ApiModelProperty("用户ID")
private Integer id;
@ApiModelProperty("用户名")
private String userName;
@ApiModelProperty("账户")
private String account;
@ApiModelProperty("密码")
private String password;
@ApiModelProperty("部门")
private String dept;
@ApiModelProperty("电话")
private String phone;
@ApiModelProperty("创建时间")
private Date createTime;
}
对应mapper.xml
<insert id="insert" parameterType="com.proton.screen.model.UserModel" useGeneratedKeys="true" keyProperty="id">
insert into user_info (user_name, account,
password, dept, phone,
create_time)
values (#{userName,jdbcType=VARCHAR}, #{account,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR}, #{dept,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR},
#{createTime,jdbcType=TIMESTAMP})
</insert>
使用
@Transactional(rollbackFor = Exception.class)
@Override
public void addUser(UserModel info) {
info.setCreateTime(new Date());
int affect = userModelMapper.insert(info);
int newId = info.getId();
if(affect <= 0) {
throw new CommonException("添加用户失败");
}
}
affect 是影响行数,插入一条数据, 所以affect = 1
newId 是插入数据库后的自增id,所以newId 是对应数据在数据库的id