【问题标题】:how to properly design "adding object to a list" using springboot with thymeleaf如何使用带有百里香叶的弹簧靴正确设计“将对象添加到列表”
【发布时间】:2019-07-10 05:50:36
【问题描述】:

我有两个类 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
}

要求是:应该允许用户通过视图添加新的食物,所以我想知道如何在视图中将 FoodType 添加到食物?

我读过这个answer,看来在视图中操作数据不是一个好主意,所以如果你是程序员,你会如何设计 MVC 层以便它能够正确处理需求?

PS:我对JS知之甚少,可以在Thymeleaf中做吗?

【问题讨论】:

  • 是的,在百里香中是可能的。我认为您的映射应该是OneToOne,因为一种食物可能有一种类型。如果在您的情况下它可能有多种类型,那么OneToMany。你可以关注这个baeldung.com/thymeleaf-list

标签: spring-boot spring-mvc thymeleaf


【解决方案1】:

您应该遵循 MVC 分层架构 以正确实现您想要的。作为一般设计指南:

  1. 向用户展示带有表单和所需输入的 UI。这是百里香叶部分。 (视图层)
  2. 使用 Controllers 捕获表单发布数据、验证输入等。
  3. 编写业务层以获取 Posted 数据并保存对象等。
  4. 使用 Service 和 Repository 接口来实现基本的 CRUD 和类似操作。

作为最后的评论;您可以将多个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

【讨论】:

  • 是的,我确实遵循 MVC 架构,我想要通过视图层将 FoodType 对象添加到 Food 对象。由于食物类型的数量可能会有所不同,我不知道如何实现这一目标
  • 您应该使用 AJAX 发布请求和 JavaScript 来执行此操作。编写 JavaScript 代码以将您的 FoodType 数据发布到控制器方法。请关注此grokonez.com/java-integration/…
猜你喜欢
  • 2021-12-11
  • 2018-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-25
  • 2020-02-19
  • 2014-05-13
相关资源
最近更新 更多