带有嵌套生成器的实体:
@Entity
@Table(name="food")
public class Food {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(name="name")
private String name;
@Column(name="type")
private String type;
@Column(name="description")
private String description;
@Column(name="date")
private LocalDate expiration;
@ManyToOne
@JoinColumn(name="container_id", foreignKey = @ForeignKey(name = "FK_FOOD"))
private Container container;
private Food(FoodBuilder foodbuilder) {
this.name = foodbuilder.name;
this.type = foodbuilder.type;
this.description = foodbuilder.description;
this.expiration = foodbuilder.expiration;
}
//getters omitted for brevity
public static class FoodBuilder {
private String name;
private String type;
private String description;
private LocalDate expiration;
public FoodBuilder(String name) {
this.name = name;
}
public FoodBuilder setType(String type) {
this.type = type;
return this;
}
public FoodBuilder setDescription(String description) {
this.description = description;
return this;
}
public FoodBuilder setExpiration(LocalDate expiration) {
this.expiration = expiration;
return this;
}
public Food buildFood(){
return new Food(this);
}
}
}
我知道如何使用 main 方法使用构建器模式创建一个新对象,即
食品食品 = 新食品.食品建设者...制定。。。构建((
但是当我通过前端的表单向我的 API 提交信息时,我一直无法找到如何使用这种模式来创建对象。
我假设您的 api 调用正在发送序列化的Food
对象,然后由控制器接收。如果您尝试通过专门使用给定的生成器将此数据反序列化为实例,Jackson 应该能够通过提供builder
参数通过JsonDeserialize
注释为您执行此操作。
如果您使用 JSP 设计了前端,请通过导入弹簧表单标签来使用弹簧表单标签。 控制器级别 您可以使用@ModelAttribute获取整个对象。 弹簧仅在所有 POJO 都需要站立时才处理嵌套对象。
工作代码(@JsonDeserialize、@JsonPOJOBuilder、@JsonCreator 和 @JsonProperty 添加(:
@Entity
@Table(name="food")
@JsonDeserialize(builder = Food.FoodBuilder.class)
public class Food {
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column(name="name")
private String name;
@Column(name="type")
private String type;
@Column(name="description")
private String description;
@Column(name="date")
private LocalDate expiration;
@ManyToOne
@JoinColumn(name="container_id", foreignKey = @ForeignKey(name = "FK_FOOD"))
private Container container;
private Food(FoodBuilder foodbuilder) {
this.name = foodbuilder.name;
this.type = foodbuilder.type;
this.description = foodbuilder.description;
this.expiration = foodbuilder.expiration;
}
//getters omitted for brevity
@JsonPOJOBuilder(buildMethodName = "build", withPrefix = "set")
public static class FoodBuilder {
private String name;
private String type;
private String description;
private LocalDate expiration;
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public FoodBuilder(@JsonProperty("name") String name) {
this.name = name;
}
public FoodBuilder setType(String type) {
this.type = type;
return this;
}
public FoodBuilder setDescription(String description) {
this.description = description;
return this;
}
public FoodBuilder setExpiration(LocalDate expiration) {
this.expiration = expiration;
return this;
}
public Food buildFood(){
return new Food(this);
}
}
}