Show data from two JPA entity tables on same page using Spring Boot and Thymeleaf

spring boot thymeleaf bootstrap 4

Let’s say you want to display multiple table contents in Spring Boot project using Thymeleaf, JPA Entity and Model.

In my project I have mapped a relationship between the two entities I need to retrieve data from and am wondering how to display data from the two tables on list page. I’ve ‘category’ table and ‘product’ table like below:

Spring Boot, Thymeleaf Show data from two JPA entity tables on same page using Spring Boot and Thymeleaf

And in my controller I’ve list of both category and product in respective model. Here is the snippet:

model.addAttribute("products", productService.findAll());
model.addAttribute("categories", categoryService.findAll());

So, I’ve all the required data in the model and I can access them from Thymeleaf. Let’s copy the table code from below (N.B: I’ve used bootstrap table):

<table class="table table-striped table-bordered table-responsive" role="grid">
   <thead>
      <th>Category</th>
      <th>Product</th>
   </thead>
   <tbody>
      <tr role="row" class="odd" th:each="product:${products}">
         <td>
            <p th:each="category : ${categories}" th:if="(${category.id} == ${product.id})" th:text="${category.name}"></p>
         </td>
         <td th:text="${product.name}">
      </tr>
   </tbody>
</table>

It’ll produce something like this:

Spring Boot, Thymeleaf: Display data from two JPA entity tables on same page

That’s all! We’re done!
If you’ve any confusion please let me know 🙂

5 thoughts to “Show data from two JPA entity tables on same page using Spring Boot and Thymeleaf”

  1. With havin so much content and articles do you ever run into any issues of plagorism or copyright infringement?
    My site has a lot of completely unique content I’ve either created myself or
    outsourced but it looks like a lot of it is popping it up all over the
    internet without my authorization. Do you know any methods to help prevent content from being stolen?
    I’d certainly appreciate it.

    1. Yeah, BlogEngine is good enough. I haven’t used it yet! BTW it doesn’t have any free theme, right?
      I’m using WordPress btw.

Leave a Reply

Your email address will not be published. Required fields are marked *