当前位置:首页 » 《随便一记》 » 正文

使用Mybatis插入数据后返回自增主键_happy488127311的博客

13 人参与  2022年03月02日 12:17  分类 : 《随便一记》  评论

点击全文阅读


有一个实体类City:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class City {
    private Integer id;

    private String name;

    private String state;

    private String country;
}

数据库表如下:

create table city
(
    id int auto_increment primary key,
    name    varchar(50) null,
    state   varchar(50) null,
    country varchar(50) null
);

controller如下

@PostMapping("/insert")
@ResponseBody
 public City insert(City city) {
     if (cityService.insert(city) > 0) {
         return city; // 返回的city有id
     } else {
         return null;
     }
 }

问题:前端传入的city没有为id赋值,现在想插入city成功后得到一个完整的City实体,即给它的id属性赋值

解决办法:在insert标签里配置属性

  • useGeneratedKeys=“true” : 开启自增主键功能
  • keyProperty=“id” : 设置自增主键

这样在返回值为int的情况下,前端传入的对象city的id也会被赋值为数据库中表的id

<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.example.boot04.bean.City" useGeneratedKeys="true">
    insert into city (`name`, `state`, country)
    values (#{name,jdbcType=VARCHAR}, #{state,jdbcType=VARCHAR}, #{country,jdbcType=VARCHAR})
 </insert>

点击全文阅读


本文链接:http://zhangshiyu.com/post/35632.html

赋值  传入  主键  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1