我一直在左右搜索,但仍然找不到一個好的解決方案。另外,我對編程還很陌生,所以請原諒我描述事情的方式:)。我正在使用 Spring、MySQL、Java、Thymeleaf。
基本上,我有一個從控制器傳遞的物件串列:
[人[代碼=1,姓名=A,車=福特1],人[id=2,姓名=A,車=福特2],人[ID=1,姓名=B,車=豐田1],人[ID= 2,名稱=B,汽車=豐田2]]
我想在 HTML 表格或引導網格系統中使用 Thymeleaf 顯示這些資料。
這是我得到的:
<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>
所以這會顯示這樣的資料:
| ID | 名稱 | 車 | 名稱 | 車 |
|---|---|---|---|---|
| 1 | 一個 | 福特1 | ||
| 2 | 一個 | 福特2 | ||
| 1 | 乙 | 豐田1 | ||
| 2 | 乙 | 豐田2 |
但我希望它顯示如下:
| ID | 名稱 | 車 | 名稱 | 車 |
|---|---|---|---|---|
| 1 | 一個 | 福特1 | 乙 | 豐田1 |
| 2 | 一個 | 福特2 | 乙 | 豐田2 |
我想我可能需要以某種方式將這些資料拆分為 id 1 和 id 2。這是我可以想到的兩種方法:
- 使用 Thymeleaf th:if="${person.id.equals(1)} 獲取 id 1 的資料,然后重復 2,我只是不知道如何將其放入表中。
- 使用查詢格式化資料,我不知道如何在不使用 GROUP_CONCAT 將結果轉換為單列的情況下執行此操作。
也許我需要更改 SQL 表,請給我一些建議。
編輯:所以我想我找到了這個MySQL 資料透視表的答案
uj5u.com熱心網友回復:
按 id 對您的人員串列進行分組。假設您有一個這樣的串列:
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")
)
分組:
Map<Integer, List<Person>> groupedByIdPersons = persons.stream().collect(Collectors.groupingBy(Person::getId));
在 Thymeleaf 中使用它:
遍歷整個地圖
th:block以創建標題。重復與按 id 分組的集合一樣多的次數。迭代整個地圖以提取鍵/值,然后只迭代中的值
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/379583.html
上一篇:java模型模擬回應json
