我正在开发一个包含两个域模型的应用程序:Student和Meal。在此应用程序中,可以通过表格创建餐点,并可以指定一名学生作为此餐的厨师。
多样性如下:
-一顿饭可以有一名学生做饭(ManyToOne)
-可以将一个学生分配给他要做的多餐(OneToMany)
现在我有两个问题,首先,每当我从数据库中删除学生时,我也要自动删除与已删除学生相对应的饭菜,我在学生的OneToMany端使用CascadeType = ALL,但是相应的餐点不会被删除。
我的代码如下:
Meal.Java
@Entity
public class Meal {
@Id
@GeneratedValue
private Long id;
@JoinColumn(name = "student_id")
@ManyToOne(fetch = FetchType.LAZY)
private Student mealCook;
private String mealName;
private int mealPrice;
数据库外观如下:https://ibb.co/RH3MGrQ
Student.Java
@Entity
public class Student {
@Id
@GeneratedValue
private Long id;
private String studentName;
@OneToMany(
mappedBy = "mealCook",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Meal> meals = new ArrayList<>();
数据库外观如下:https://ibb.co/vjSST6g
MealController.Java
@Controller
@RequestMapping("/m")
public class MealController {
@Autowired
private MealService mealService;
private final MealRepository mealRepository;
private final StudentRepository studentRepository;
public MealController(MealRepository mealRepository, StudentRepository studentRepository){
this.mealRepository = mealRepository;
this.studentRepository = studentRepository;
}
@GetMapping(params = "form")
public String createForm(@ModelAttribute Meal meal , Model model) {
Iterable<Student> students = this.studentRepository.findAll();
model.addAttribute("students" , students);
return "meals/form";
}
@PostMapping
public ModelAndView create(@Valid Meal meal, BindingResult result,
RedirectAttributes redirect) {
if (result.hasErrors()) {
return new ModelAndView("meals/form", "formErrors", result.getAllErrors());
}
meal = this.mealRepository.save(meal);
redirect.addFlashAttribute("globalMessage", "meals.view.success");
return new ModelAndView("redirect:/m/{meal.id}", "meal.id", meal.getId());
}
我的第二个问题是我想显示特定学生正在烹饪的所有饭菜,但是我的数据库不会显示与该学生链接的饭菜ID。我为要实现的目标添加了屏幕截图:https://ibb.co/2s6rMqt
我的问题是,如何在学生表中显示一列饭菜ID?
我希望我已经清楚地说明了我的问题,谢谢!!