我只需要从表1中提取与表2中的数据相关的特定数据,例如:
让我们说“菜单”表中有两行-“比萨饼”和“薯条” 在“成分表”中,我有3行-“奶酪”,“土豆”,“酱”
“ Pizza”通过第三张表的外键连接到“ Cheese”和“ Sauce”,而“ Fries”连接到“ Potato”,现在我只想显示“ menu”表和“ Ingredients”中的数据互相连接的桌子。
例如:
Pizza-“奶酪”,“酱”
薯条-“土豆”
到目前为止,我只能列出两个表中的数据(所有数据),我无法选择显示哪些数据。
胸腺:
<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";
}
Menu.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
Ingredient.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;
答案 0 :(得分:0)
由于Menu
与Ingredients
有关联,因此它将包含链接的成分。您无需分别获取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 : ${menu.ingredient}"> <!-- I have only modified here -->
<ul>
<li th:text = ${ing.ingredientName}></li>
</ul>
</td>