Mybatis获取自动增加Id

Mybatis获取自动增加Id

MyBatis成功插入后获取自动增加的id

一、向xxMapping.xml配置中加上两个配置。
<insert id="insertUser" useGeneratedKeys="true" keyProperty="id" parameterType="UserEntity">
        INSERT INTO USER VALUES(null,#{userName},#{password},#{realName})
    </insert>

其中keyProperty的值就是数据库中自增加字段名。java

二、在Controller插入方法中,插入成功后,直接经过model的get的方法就能得到自增加的id值。
@RequestMapping("addUser")
public String addUser(@ModelAttribute UserEntity userEntity) {
    int i = userService.insertUser(userEntity);//插入记录到数据库,userEntity中没有设置id的值
    String result = "";
    if (i > 0) {
        result = "inster User SUCCESS!!! ID: " + userEntity.getId();//插入成功后,将自增加的id存入到原来的model中,经过get方法就能拿到自增加的id了
    } else {
        result = "inster User FAIL!!!";
    }
    return result;
}
相关文章
相关标签/搜索