1. 程式人生 > >mybatis插入返回自增主鍵

mybatis插入返回自增主鍵

昨天下班到家以後收到一朋友問我一個問題:mysql中設定的是自增主鍵,然後在Mybatis執行insert語句後如何返回自增主鍵值,我說明天我到公司後寫一篇部落格給你

Mybatis官網是這樣說的:

First, if your database supports auto-generated key fields (e.g. MySQL and SQL Server), then you can simply set useGeneratedKeys="true" and set the keyProperty to the target property and you're done. For example, if the Author

table above had used an auto-generated column type for the id, the statement would be modified as follows:

就是說需要useGenerateKeys=“true”和keyProperty=“XXId”,但是需要下面這些前置條件

1、升級Mybatis版本到3.3.1。

2、在Dao中不能使用@param註解。

一、單條insert返回自增主鍵,方案一

好了廢話不多說,直接上程式碼

user.xml

<insert id="insert" parameterType="com.test.User">
INSERT INTO User <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null" >taskScheduleId,</if> <if test="userName != null" >clearSettleFileId,</if> <if test="age!= null" >inputDate,</if> <if test="address != null"
>fileDate,</if> </trim> <trim prefix="VALUES (" suffix=")" suffixOverrides="," > <if test="id != null" >#{id,jdbcType=INTEGER},</if> <if test="userName != null" >#{userName,jdbcType=VARCHAR},</if> <if test="age != null" >#{age,jdbcType=VARCHAR},</if> <if test="address != null" >#{address,jdbcType=VARCHAR},</if> </trim> <selectKey resultType="java.lang.Integer" keyProperty="id"> SELECT LAST_INSERT_ID() AS id     </selectKey> </insert>

UserServiceImpl.java

User vo = new User();
vo.setUserName("zhangsan");vo.setAge("20");
vo.setAddress("a");dao.insert("insert",vo);

System.out.println(vo.getId());

二、單條insert返回自增主鍵,方案二

就是xml但變動,java類不需要變動

<insert id="insert" parameterType="com.test.User" keyProperty="taskScheduleId" useGeneratedKeys="true">
INSERT INTO User
     <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="id != null" >taskScheduleId,</if>
        <if test="userName != null" >clearSettleFileId,</if>
        <if test="age!= null" >inputDate,</if>
        <if test="address != null" >fileDate,</if>    </trim>
    <trim prefix="VALUES (" suffix=")" suffixOverrides="," >
        <if test="id != null" >#{id,jdbcType=INTEGER},</if>
        <if test="userName != null" >#{userName,jdbcType=VARCHAR},</if>
        <if test="age != null" >#{age,jdbcType=VARCHAR},</if>
        <if test="address != null" >#{address,jdbcType=VARCHAR},</if>    </trim>
</insert>

二、批量插入insert返回自增主鍵

user.xml

<insert id="insertBatch" parameterType="list" keyProperty="id" useGeneratedKeys="true">
INSERT INTO User(
        userName,
        age,
        address)VALUES
        <foreach collection="list" item="item" separator="," index="index">
            <trim prefix="(" suffix=")" suffixOverrides=",">
            #{item.userName,jdbcType=VARCHAR},
            #{item.age,jdbcType=VARCHAR},
            #{item.address,jdbcType=VARCHAR}
            </trim>
        </foreach>
</insert>