首页 > 学院 > 开发设计 > 正文

MyBatis+MySQL返回插入的主键ID

2019-11-14 15:41:39
字体:
来源:转载
供稿:网友

需求:使用MyBatis往MySQL数据库中插入一条记录后,需要返回该条记录的自增主键值。

方法:在mapper中指定keyPRoperty属性,示例如下:

1 <insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.koala.blog.model.Test" >2     insert into test (id, name)3     values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR})4   </insert>

如上所示,我们在insert中指定了keyProperty="id",其中id代表插入的Test对象的主键属性。

还要明确useGeneratedKeys="true"否则也不会起作用

model,dao皆由mybatis generator自动生成

使用单元测试测试的方法:

1 @Test2 public void testInsert() {3     com.koala.blog.model.Test test = new com.koala.blog.model.Test();4     test.setName("haha");5     int result = testService.insert(test);// result是指插入几条记录6     LOGGER.info(test.getId());// test.getId()是获取新增记录的主键7 }

该方法适用于主键为int型的自增主键

非自增主键需要设置主键后才能正确插入数据,所以配不配置   useGeneratedKeys="true" keyProperty="id"

都可以正确获取  test.getId()


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表