[英]Handling POST requests within Spring
我目前正在编写一个利用 JPA 的 spring 应用程序。 但是,我对如何处理 POST 请求感到困惑。 我有一件带有 Brand 变量的 class 服装:
@Entity
@Table(name = "CLOTHING")
public class Clothing {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id;
private String name;
private String imageURL;
private String productURL;
@ManyToMany(mappedBy = "items", fetch = FetchType.EAGER)
@JsonBackReference
private List<MedianGroup> groups;
@OneToOne()
@JoinColumn(name = "brand_id", referencedColumnName = "id")
private Brand brand;
@OneToMany()
@JoinColumn(name = "like_id", referencedColumnName = "id")
@JsonManagedReference
private List<Like> likes;
private ClothType type;
private Gender gender;
protected Clothing() {}
public Clothing(String name, String imageURL, String productURL, Brand brand, ClothType type, Gender gender) {
this.name = name;
this.imageURL = imageURL;
this.productURL = productURL;
this.brand = brand;
this.type = type;
this.gender = gender;
}
@Entity
@Table(name = "BRAND")
public class Brand {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id;
private String name;
private String URL;
创建新服装项目的发布请求处理是:
@PostMapping("/clothing")
ResponseEntity<?> newItem(@RequestBody Clothing newItem) {
System.out.println(assembler.toModel(newItem));
EntityModel<Clothing> entityModel = assembler.toModel(repository.save(newItem));
return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()).body(entityModel);
}
我希望找到一种使用 JSON 字符串作为请求正文并将品牌存储在变量中的方法。 有没有办法做到这一点? 我自己解析 JSON 字符串会更好吗?
更好地使用 DTO,参考这里https://www.javaguides.net/2021/02/spring-boot-dto-example-entity-to-dto.html 。 读取数据后,创建两个实体对象——从 DTO 读取数据并分配引用。 然后进行保存调用以进行关联。 参考https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-one-mapping-example/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.