【发布时间】:2019-06-09 19:04:58
【问题描述】:
我只需要从表 1 中提取与表 2 中的数据相关联的特定数据。例如:
假设在“菜单”表中我有 2 行 - “披萨”和“薯条” 在“Ingredients table”中,我有 3 行 - “Cheese”、“Potatoes”、“Sauce”
“Pizza”使用第三表的外键连接到“Cheese”和“Sauce”,“Fries”连接到“Potato”,现在我只想显示“menu”表和“Ingredients”中的数据相互连接的表。
例如:
比萨 - “奶酪”、“酱汁”
薯条 - “土豆”
到目前为止,我只能列出两个表中的数据(所有数据),我无法选择显示哪些数据。
百里香:
<tr th:each="menu : ${menuList}">
<td th:text="${menu.name}"></td>
<td><a th:href="@{/foodDescription}" th:text="Description">Description</a></td>
<td th:each="ing : ${ingredientList}">
<ul>
<li th:text = ${ing.ingredientName}></li>
<!-- Here I only want to display ingredientName and description which
are connected to the specific ${menu.name} -->
</ul>
</td>
</tr>
控制器:
@Controller
public class MyController{
@Autowired
MenuRepository menuRepository;
@Autowired
IngredientRepository ingredientRepository;
@GetMapping("/hello")
private String hello(){
return "hello-page";
}
@GetMapping("/recipeList")
public String listPage(Model model){
model.addAttribute("menuList",menuRepository.findAll());
model.addAttribute("ingredientList", ingredientRepository.findAll());
return "list-page";
}
菜单.java:
@Entity
@Table(name = "menu")
public class Menu {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
// Mapping To second table
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "menu_ingredient",
joinColumns = @JoinColumn(name = "menu_id"),
inverseJoinColumns = @JoinColumn(name = "ingredient_id"))
private List<Ingredients> ingredient = new ArrayList<>();
// Constructor/Getter/Setter/ToString
成分.java:
@Entity
@Table(name = "ingredients")
public class Ingredients {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "ingredient")
private String ingredientName;
@Column(name = "description")
private String ingredientDescription;
【问题讨论】:
-
考虑迭代
List<Ingredients>,它已经包含在Menu实例中。这将避免必须在模板中进行任何过滤。侧边栏:类名有些混乱——Ingredients是复数,但实际上代表单一成分。Menu(作为物理对象)表示可以订购多个物品的容器,例如,MenuItem可能是一个更好的名称。那么Menu可以包含List<MenuItem> menuItems,MenuItem可以包含List<Ingredient> ingredients。
标签: java mysql spring-boot thymeleaf