Mybatis-XML插入新纪录并返回自增主键id

—— Mybatis入门写法记录

momo314相同方式共享非商业用途署名转载

菜鸡记录Mybatis插入一天新纪录并且同时返回自增主键id的写法,感觉还是挺常用的,备查。

上代码,不废话

首先在mapper中定义一个方法(表名:student):

public interface StudentMapperExt extends StudentMapper {
/**
* 插入新记录并返回自增主键id
*/
Integer insertAndGetPrimaryKey(Student student);
}

然后再对应的xml中增加SQL实现:

<insert id="insertAndGetPrimaryKey"
parameterType="com.namespace.domain.Student"
keyProperty="id"
useGeneratedKeys="true">
insert into student
(`name`, age, gender)
values
(
#{name, jdbcType=INTEGER},
#{age, jdbcType=NVARCHAR},
#{gender, jdbcType=INTEGER}
)
</insert>

总结

  • Mybatis-XML中insert节点中,用属性keyProperty来指定自增列在实体类中对应的列名
  • 将属性useGeneratedKeys设置为true,来将JDBC设置为支持自动生成主键,并可将自动生成的主键返回
✎﹏ 本文来自于 momo314和他们家的猫,文章原创,转载请注明作者并保留原文链接。
收藏文章
表情删除后不可恢复,是否删除
取消
确定
图片正在上传,请稍后...
  • 评分:
评论内容为空!
还没有评论,快来抢沙发吧!