有一個物體類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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/305274.html
標籤:其他
