MyBatis插入数据时获取自增主键的值

在我们录入数据时,针对某些记录比如用户信息之类的数据,我们往往需要同时在其关系表中更新数据。在更新数据的过程中记录的某些字段可能是自增涨序列,这时候我们就学要使用MyBatis中获取主键的方法

 

第一步:

在Mapper文件中设置useGeneratedKeyskeyProperty两个属性,其中“keyProperty”值为JAVA对象的属性名;示例如下:

<insert id="addUser" parameterType="User" useGeneratedKeys="true"
        keyProperty="id">
        INSERT INTO
        user(username,loginName,phone,gender,email,description,password,status,update_time,create_time)
        values(#{username},#{loginName},#{phone},#{gender},#{email},#{description},#{password},#{status},NOW(),NOW())
    </insert>

第二步:

 此时JAVA对象中的id属性已经被赋值为字段自增长所得的值,接下来的储存直接使用该对象就行;

  <insert id="aaa" parameterType="User" >
        INSERT INTO
        aaa (a,b) values (#{id},#{b})
    </insert>
    <insert id="bbb" parameterType="User" >
        INSERT INTO
        bbb (a,b) values (#{a},#{id})
    </insert>

 

posted @ 2018-03-13 14:24  vike0906  阅读(773)  评论(0编辑  收藏  举报