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

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

    方法:在mapper中指定keyProperty属性,示例如下:

    1 <insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.koala.blog.model.Test" >
    2     insert into test (id, name)
    3     values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR})
    4   </insert>

    如上所示,我们在insert中指定了keyProperty="id",其中id代表插入的Test对象的主键属性。

    还要明确useGeneratedKeys="true"否则也不会起作用

    model,dao皆由mybatis generator自动生成

    使用单元测试测试的方法:

    1 @Test
    2 public void testInsert() {
    3     com.koala.blog.model.Test test = new com.koala.blog.model.Test();
    4     test.setName("haha");
    5     int result = testService.insert(test);// result是指插入几条记录
    6     LOGGER.info(test.getId());// test.getId()是获取新增记录的主键
    7 }

    该方法适用于主键为int型的自增主键

    非自增主键需要设置主键后才能正确插入数据,所以配不配置   useGeneratedKeys="true" keyProperty="id"

    都可以正确获取  test.getId()

  • 相关阅读:
    jenkins代码自动部署
    jenkins安装
    git图形管理工具
    gitlab自动备份恢复与卸载
    linux下获取外网IP
    网站安全webshell扫描
    jQuery动画效果实现
    form表单中的enctype属性什么意思?
    你那么努力又怎么样!
    话语
  • 原文地址:https://www.cnblogs.com/draenei/p/4791513.html
Copyright © 2011-2022 走看看