我是Spring和JPA的新手,我一直在关注诸如this这样的教程
我已经在我的应用程序上下文中应用了相同的想法,因此我将食品和配料作为模型类。
我通过扩展JpaRepository创建了FoodRepository,并且创建了FoodController,当我添加没有配料的食物时,它工作正常,该类看起来像这样:
@RestController
@RequestMapping("/api")
public class FoodController {
@Autowired
FoodRepository foodRepository;
@GetMapping("/food")
public List<Food> getAllFoods() {
return foodRepository.findAll();
}
@PostMapping("/food")
public Food createFood(@Valid @RequestBody Food food) {
return foodRepository.save(food);
}
@GetMapping("/food/{id}")
public Food getFoodById(@PathVariable(value = "id") Long foodId) {
return foodRepository.findById(foodId)
.orElseThrow(() -> new CRSException("Could not find the food with id: " + foodId));
}
@PutMapping("/food/{id}")
public Food updateFood(@PathVariable(value = "id") Long foodId, @Valid @RequestBody Food foodDetails) {
Food food = foodRepository.findById(foodId)
.orElseThrow(() -> new CRSException("Could not find the food with id: + foodId)"));
food.updateFood(foodDetails);
Food updatedFood = foodRepository.save(food);
return updatedFood;
}
@DeleteMapping("/food/{id}")
public ResponseEntity<?> deleteFood(@PathVariable(value = "id") Long foodId) {
Food food = foodRepository.findById(foodId)
.orElseThrow(() -> new CRSException("Could not find the food with id: + foodId)"));
foodRepository.delete(food);
return ResponseEntity.ok().build();
}
}
我基本上想保存包含成分列表的食物,但是我不知道如何修改createFood的签名,以便我可以将成分列表参数带入方法并使用这些成分保存食物。 / p>
由于我是Spring Boot的新手,因此jpa和hibernate都可以使用;我不知道搜索时使用什么术语。如何实现呢?
感谢您的帮助
预先感谢
答案 0 :(得分:0)
您可以通过以下方式为每种成分设置食物参考:
@PostMapping("/food")
public Food createFood(@Valid @RequestBody Food food) {
food.getIngredients().foreach((i) -> {i.setFood(food)});
return foodRepository.save(food);
}
需要考虑到您的实体Food具有以下价值:
@OneToMany(mappedBy = "food", cascade = CascadeType.ALL)
private List<Ingredients> ingredients;