I'm trying to create a web page using a thymeleaf template to present a table of Orders with a field that provided a list of products associated with a specific order.
My controller class:
@Controller
public class WebPage {
@Autowired
private OrderRepository orderRepository;
@Autowired
private ProductRepository productRepository;
@RequestMapping("/test")
public String index(Model model) {
model.addAttribute("ordertable", orderRepository.findAll());
model.addAttribute("producttable", productRepository.findAll());
return "tablepage";
}
}
Relevant part of thymeleaf template:
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>stuff</th>
<th>Stuuff</th>
<th>stuff</th>
<th>products</th>
</tr>
</thead>
<tbody>
<tr th:each="ordertbl: ${ordertable}">
<td th:text="${ordertbl.stuffId}"/>
<td th:text="${ordertbl.stuffname}"/>
<td th:text="${ordertbl.stuffname}"/>
<td th:text="${ordertbl.stuff}"/>
<td>
<span th:each="producttbl: ${producttable}"><span th:text="${ordertbl.products}"/></span>
</td>
</tr>
</tbody>
</table>
What this does is creates a table of orders but in the final field, it lists all the products contained in the order several times depending how many products are in the product table.
How would I change this so that the the order field lists the products belonging to each row just once. I am aware that this is most likely a nested for loop error, or a problem with my use of findall()
method but I'm not sure how to fix it.
I would prefer to use the nested product table rather than fetching the products from the order jpa entity class. Thanks.