java - 多个相同长度的模型同时迭代
问题描述
我有一个非常特殊的问题,与春季启动中的百里香有关,使用 Java Persitence API (JPA)。
我有三个表(A、B、C),因此模型,它们看起来像这样:
A:
@Entity
@Table(name = "A")
public class ATable {
private int aid;
private String acontent;
// getters and setters
}
乙:
@Entity
@Table(name = "B")
public class BTable {
private int bid;
private String bcontent;
// getters and setters
}
C:
@Entity
@Table(name = "C")
public class CTable {
private int cid;
private String ccontent;
// getters and setters
}
根据设计,这三个表将具有相同数量的内容。
表的行是这样的:
A:
帮助内容
1 a1 2 a2 3 a3
乙:
投标内容
1 b1 2 b2 3 b3
C:
cid 内容
1 c1 2 c2 3 c3
现在,我想在我的 HTML5 模板中同时遍历这三个表,结果应该是这样的:
a1 b1 c1
b1 b2 b3
c1 c2 c3
我的控制器是这样的:
...
List<ATable> atable = new ArrayList<>();
model.addAttribute("atable", atable);
List<ATable> atables = atableRepository.findAll();
model.addAttribute("atables", atables);
List<BTable> btable = new ArrayList<>();
model.addAttribute("btable", btable);
List<BTable> btables = btableRepository.findAll();
model.addAttribute("btables", btables);
List<CTable> ctable = new ArrayList<>();
model.addAttribute("ctable", ctable);
List<CTable> ctables = ctableRepository.findAll();
model.addAttribute("ctables", ctables);
...
要仅遍历其中一个表,我可以这样:
<tr th:each="atable : ${atables}">
<span th:text="${atable.acontent}">
</tr>
但是我们怎样才能同时使用三个表呢?
我想我对代表我的问题的表格已经足够清楚了,我真的希望有人可以帮助我。提前致谢。
解决方案
创建一个代表 HTML 中一行的 DTO:
public class Row {
private ATable atable;
private BTable btable;
private CTable ctable;
// constructor + getters here
}
然后在你的控制器中使用它:
@GetMapping
public String showPage(Model model) {
List<ATable> atables = atableRepository.findAll();
List<BTable> btables = btableRepository.findAll();
List<CTable> ctables = ctableRepository.findAll();
List<Row> rows = new ArrayList<>();
for( int i = 0; i < atables.size();i++) {
rows.add(new Row(atables.get(i), btables.get(i), ctables.get(i));
}
model.addAttribute("rows", rows);
}
现在在 Thymeleaf 中遍历您的行:
<tr th:each="row : ${rows}">
<span th:text="${row.atable.acontent}">
<span th:text="${row.btable.acontent}">
<span th:text="${row.ctable.acontent}">
</tr>
推荐阅读
- javascript - 如果用户没有按下按钮,则阻止步进表单
- android - 哪款 Android 设备具有 BIOMETRIC_STRONG(第 3 类)人脸身份验证?
- dll - 如何在 BtsCatalogExplorer 中查找管道组件?
- javascript - 是否有扩展或方法来突出显示 laravel Blade 指令 @section .... @end 代码中的代码中的正确代码?
- matlab - 在其他方法中访问从类的方法返回的数据
- javascript - 如果我移动硬编码的引号,查询将不起作用
- image - CV_bridge 压缩图像?
- android - React Native - 用于 Android AAB 生成的 build.gradle 配置
- python - RMSE 比较两个以上的数据样本?
- java - 拆分函数在java中给出不正确的结果