zoukankan      html  css  js  c++  java
  • MyBatis+MySQL 返回插入的主键ID

    一.需求:

    使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。

    二.使用:

    1.实体类:

    public class User {
        private int userId;
        private String userName;
        private String password;
        private String comment;
    }

    2.mapperXml代码:

    <insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
        insert into user(userName,password,comment)
        values(#{userName},#{password},#{comment})
    </insert>

    useGeneratedKeys:

      取值范围true|false

      默认值是:false。

      含义:设置是否使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。

    keyProperty:

      在insert中指定了keyProperty="userId",其中userId代表插入的User对象的主键属性。

    3.测试代码:

    User user = new User();
    user.setUserName("chenzhou");
    user.setPassword("xxxx");
    user.setComment("测试插入数据返回主键功能");
    
    System.out.println("插入前主键为:"+user.getUserId());    //输出:0
    userDao.insertAndGetId(user);//插入操作
    System.out.println("插入后主键为:"+user.getUserId());    //输出:4

    转自:https://blog.csdn.net/weixin_38553453/article/details/80506935

  • 相关阅读:
    第六章:单元测试框架unittest
    Jenkins 使用 war包安装时,如果出现报离线错误解决方法
    Appium自动化封装教案
    yaml文件读取(5.1之前与5.1之后对比)
    appium-desktop配置运用方法
    postwoman 配置
    jwt解析
    pytest
    centos安装python3.8
    linux 查找命令
  • 原文地址:https://www.cnblogs.com/XueTing/p/14052915.html
Copyright © 2011-2022 走看看