Issue
I have been searching left and right but still can't find a good solution to this. Also I'm pretty new to programing so please excuse the way I describe thing :). I'm using Spring, MySQL, Java, Thymeleaf.
Basically, I have a list of object passed from the controller:
[person [code=1, name=A, car=ford1],person [id=2, name=A, car=ford2], person [id=1, name=B, car=toyota1], person [id=2, name=B, car=toyota2] ]
I want to display this data using Thymeleaf in either an HTML table or bootstrap grid system.
This is what I got:
<div>
<table
class="
table table-bordered table-striped table-hover table-responsive-xl
"
>
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Name</th>
<th>Car</th>
<th>Name</th>
<th>Car</th>
</tr>
</thead>
<tbody>
<tr th:each="person :${listOfPerson}">
<td>
[[${person.id}]]
</td>
<td>
[[${person.name}]]
</td>
<td>
[[${person.car}]]
</td>
</tr>
</tbody>
</table>
</div>
so this display the data like this:
ID | Name | Car | Name | Car |
---|---|---|---|---|
1 | A | ford1 | ||
2 | A | ford2 | ||
1 | B | toyota1 | ||
2 | B | toyota2 |
but I want it to display like this:
ID | Name | Car | Name | Car |
---|---|---|---|---|
1 | A | ford1 | B | toyota1 |
2 | A | ford2 | B | toyota2 |
I think I probably need to somehow split this data into id 1 and id 2. Here is two ways I could think of doing this:
- Using Thymeleaf th:if="${person.id.equals(1)} to get the data for id 1 and then repeat for 2, I just don't know how to put this into the table.
- format the data using a query, I'm not sure how to do this without turning the result into one single column with GROUP_CONCAT.
Maybe I need to change the SQL table, please give me some suggestion.
Edit: So I think I found the answer to this MySQL pivot
Solution
Group your list of persons by id. Let's say you have a list like this:
List<Person> persons = Arrays.asList(
new Person(1, "A", "ford1"),
new Person(2, "A", "ford2"),
new Person(1, "B", "toyota1"),
new Person(2, "B", "toyota2")
)
Group it:
Map<Integer, List<Person>> groupedByIdPersons = persons.stream().collect(Collectors.groupingBy(Person::getId));
Use it in Thymeleaf:
Iterate over whole map in
th:block
to create header. Repeats as many times as there are collections grouped by the id.Iterate over whole map to extract both key/value, then iterate only over values in
th:block
<thead>
<tr>
<th:block th:each="elem : ${groupedByIdPersons}">
<th>ID</th>
<th>Name</th>
<th>Car</th>
</th:block>
</tr>
</thead>
<tbody>
<tr th:each="elem : ${groupedByIdPersons}">
<th:block th:each="person : ${elem.value}">
<td>${person.id}</td>
<td>${person.name}</td>
<td>${person.car}</td>
</th:block>
</tr>
</tbody>
Answered By - Branislav Lazic
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.