1. 程式人生 > >Mybatis + MySql 插入時獲取自增的主鍵

Mybatis + MySql 插入時獲取自增的主鍵

MyBatis 3.2.6插入時候獲取自增主鍵方法有二

以MySQL5.5為例:

方法1:

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

方法2:

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

插入前實體id屬性為0;

插入後實體id屬性為儲存後自增的id;

注意點:

方法1中的keyProperty指物件的的屬性名稱,不是資料庫中的列名,如果parameterType在Dao中的引數名稱為param,則keyProperty="param.id"

方法2中的keyProperty也是如此