使用Mybatis插入数据后返回自增主键

有一个实体类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>

你可能感兴趣的:(java,数据库,mybatis,spring,boot)