我有两个类Food和FoodType:
public class Food {
//other attributes and constructor and getters and setters are ignored
@ManyToMany(targetEntity = FoodType.class, fetch = FetchType.LAZY)
@JoinTable(name = "food_type_",
joinColumns = {@JoinColumn(name = "fid")},
inverseJoinColumns = {@JoinColumn(name = "tid")})
private List<FoodType> types = new ArrayList<>();
}
public class FoodType {
@Id
@GeneratedValue
private long id;
private String type;
@ManyToMany(targetEntity = Food.class, fetch = FetchType.LAZY, mappedBy = "types")
private List<Food> foodList = new ArrayList<>();
//constructor and getters and setters are ignored
}
要求是:应该允许用户通过视图添加新食品,因此我想知道如何在视图中向Food添加FoodType?
我已经读过这个answer,在视图中操作数据似乎不是一个好主意,因此,如果您是程序员,将如何设计MVC层以使其能够满足要求好吗
PS:我对JS知之甚少,有可能在Thymeleaf中做到吗?
答案 0 :(得分:0)
您应该遵循 MVC分层体系结构,以正确实现所需的目标。作为一般设计准则:
最后一句话;将多个FoodType
保存到单个Food
对象的操作如下(在控制器或业务逻辑层中,您可以这样做):
Food aFood = new Food(); // Empty Food to save
aFood.types.add(new FoodType(id, "Pizza"));
aFood.types.add(new FoodType(id, "Burger"));
foodService.save(aFood); // Assuming you are using Service Layer