需求:使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。
方法1(推介使用):在mapper中指定keyProperty属性,示例如下:
<insert id="insert" parameterType="com.cl.media.model.Advert"
useGeneratedKeys="true" keyProperty=advertId">
insert into r_advert
(advert_id, org_id, title,image, `url`)
values (#advertIdjdbcType=BIGINT},#{orgId,jdbcType=BIGINT},#{title,jdbcType=VARCHAR},
#{image,jdbcType=VARCHAR},#{url,jdbcType=VARCHAR})
</insert>
方法2:在mapper中指定keyProperty属性,示例如下:
<insert id="insert" parameterType="com.cl.media.model.Advert">
<selectKey resultType="java.lang.Long" order="AFTER" keyProperty="advertId">
SELECT LAST_INSERT_ID() AS advertId
</selectKey>
insert into r_advert
(advert_id, org_id, title,image, `url`)
values (#advertIdjdbcType=BIGINT},#{orgId,jdbcType=BIGINT},#{title,jdbcType=VARCHAR},
#{image,jdbcType=VARCHAR},#{url,jdbcType=VARCHAR})
</insert>
如上所示,我们在insert中指定了keyProperty="advertId",其中advertId代表插入的Advert对象的主键属性。
Advert.java
public class Advert {
private Long advertId;
private Long orgId;
private String title;
private String image;
private String url;
}
测试:
System.out.println("插入前:"+advert.getAdvertId());
int insert = dao.insert(advert);
System.out.println("插入后:"+advert.getAdvertId());
输出:
插入前:null
插放后: 34