MyBatis插入語句獲取主鍵id
阿新 • • 發佈:2019-02-10
解決問題:insert後需要用到自動生成的主鍵"id"
解決方法:
<!-- 直接寫到insert語句中 -->
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID()
</selectKey>
在外面直接用 物件.getId 獲得返回的值
使用示例:
<insert id="insertSelective" parameterType="po.TTask"> <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() </selectKey> insert into t_task <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="username != null"> username, </if> <if test="stat != null"> stat, </if> <if test="ts != null"> ts, </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="stat != null"> #{stat,jdbcType=INTEGER}, </if> <if test="ts != null"> #{ts,jdbcType=TIMESTAMP}, </if> </trim> </insert>