一、 Mybatis可以获取插入记录的自增长主键ID(程序执行插入操作后返回自增id,作为参数的实体类自动更新)
1.在插入语句<insert>标签中添加属性“useGeneratedKeys”和“keyProperty”,其中keyProperty是Java对象的属性名,而不是数据表的字段名。
1 <insert id="insertPartnerUser" parameterType="com.paycloud.interfaces.dto.PartnerUserDto" useGeneratedKeys="true" keyProperty="puid"> 2 insert into wp_partners_user 3 <trim prefix="(" suffix=")" prefixOverrides=","> 4 <if test="partnerId != null and partnerId != ''">, PARTNER_ID </if> 5 <if test="partnerName != null and partnerName != ''">, PARTNER_NAME </if> 6 </trim> 7 <trim prefix="VALUES (" suffix=")" prefixOverrides=","> 8 <if test="partnerId != null and partnerId != ''">, #{partnerId} </if> 9 <if test="partnerName != null and partnerName != ''">, #{partnerName} </if> 10 </trim> 11 </insert >
2.Mybatis执行完插入SQL语句后,自动将自增长主键赋值给对象JavaBean的属性puid。然后,通过 PartnerUserDto 对应的getter方法可获取puid值!
Integer puid = PartnerUserDto.getPuid();