mysql + mybatis 实现主键自增

一, mybatis 对应的特定表 (Customer) 的配置

1, 代码

  <insert id="insertSelective" parameterType="Customer"
     keyProperty="customerid" useGeneratedKeys="true" >

    insert into im_customer
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="customercode != null" >
        CustomerCode,
      </if>
      <if test="customername != null" >
        CustomerName,
      </if>
      <if test="customerlocation != null" >
        CustomerLocation,
      </if>
    </trim>

    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="customercode != null" >
        #{customercode,jdbcType=VARCHAR},
      </if>
      <if test="customername != null" >
        #{customername,jdbcType=VARCHAR},
      </if>
      <if test="customerlocation != null" >
        #{customerlocation,jdbcType=VARCHAR},
      </if>
    </trim>

  </insert>

2, 解释

keyProperty是Java对象的属性,其对应于数据库中指定表的主键字段;

useGeneratedKeys 参数只针对 insert 语句生效,默认为 false。

① keyProperty 和 useGeneratedKeys 一起使用

如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),那么你可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置到目标属性上就OK了。

<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username,password,email,bio)
  values (#{username},#{password},#{email},#{bio})
</insert>

② 只使用keyProperty,不使用useGeneratedKeys,就需要配合<selectKey >使用

<insert id="insertAuthor">
  <selectKey keyProperty="id" resultType="int" order="BEFORE">
    select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
  </selectKey>
  insert into Author
    (id, username, password, email,bio, favourite_section)
  values
    (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>

二, 执行


1, 这样配置完了之后,运行程序并不能想象那样就成功了,第一次插入的时候必须要在mysql数据库里执行一下主键自增的语句,才能如愿以偿的新增成功,

alter table student  modify studnet_id  integer auto_increment    ,student表名,student_id 是主键。

2,mysql设置ID增值起始值的语句:

alter table student AUTO_INCREMENT=1000

 

 

  1. useGenerateKey:开启返回自增列
  2. KeyProperty:返回自增列,对象对应的属性,
  3. 自增列值获取:自增主键会映射到对象对应的属性中
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值