POSTMAN
我的头"内容类型"是"application/json",我用json原始发送它,看起来像这样。。。
{
"category": "House Maintenance"
}
应用程序
类别.java(模型(
@Data
@Entity
@Table(name = "Categories")
public class Category implements Serializable{
private static final long serialVersionUID = -8577891700634111561L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@Column(name = "category", nullable = false)
private String category;
public Category(String category){
super();
this.category = category;
}
public Category(){
}
}
CategoryServiceImpl.java(保存方法(
@Override
public void save(Category newCategory) {
categoryRepository.save(newCategory);
}
CategoryController.java(请求(
@RequestMapping(value = "/categories", method = RequestMethod.POST)
public void addCategory(@RequestBody String categoryName){
Category newCategory = new Category(categoryName);
categoryService.save(newCategory);
}
您正在控制器方法中将请求转换为String,因此您将接收请求的整个主体,并将类别字段设置为整个json字符串。
你想做的是Spring Boot已经为你提供了转换后的dto:
@RequestMapping(value = "/categories", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void addCategory(@RequestBody Category category){
categoryService.save(category);
}
如果你不想将你的实体与请求耦合,你需要引入一个额外的类,例如CreateCategoryDto
:
@Data
public class CreateCategoryDTO{
@JsonProperty(value = "category")
private String category;
}
(我假设您使用的是Lombok和Jackson。添加注释@JsonProperty(value = "category")
只是为了说明如何将Java字段名称与Json名称解耦。(
然后控制器变成
@RequestMapping(value = "/categories", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void addCategory(@RequestBody CreateCategoryDto categoryDto){
Category newCategory = new Category(categoryDto.getCategory());
categoryService.save(newCategory);
}
回答
多亏了拉尔夫·瓦格纳,我回去把我的方法改成了以下。
//Old
method(@RequestBody String category)
//New
method(@RequestBody Category category)
我在"Category"模型中添加了"@JsonProperty",以避免创建额外的类。
//Old
@Column(name = "category", nullable = false)
private String category;
//New
@Column(name = "category", nullable = false)
@JsonProperty(value = "category")
private String category;
我的数据库现在存储正确。