MyBatis插入时候获取自增主键方法

 

方法一:(Oralce不支持这种写法)

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

  keyProperty 的值必须为数据库中主键且是自动增长的字段。(一般是 id 字段)

<insert id="insert" parameterType="Person" useGeneratedKeys="true" keyProperty="id">
        insert into person(name,pswd) values(#{name},#{pswd})
</insert>

 

方法二:

<insert id="insert" parameterType="Person">
    <selectKey keyProperty="id" resultType="long">
      select LAST_INSERT_ID()
   </selectKey>
  insert into person(name,pswd) values(#{name},#{pswd})
</insert>

 

如上是个User实体类,有id,name,pswd 三个属性。id为字段增长的主键。在插入操作时如以上的写法主键id就不需要赋值,会自动赋值。

 

posted @ 2017-11-14 17:10  大大大圣  阅读(666)  评论(0编辑  收藏  举报