首页 > 解决方案 > 多个相同长度的模型同时迭代

问题描述

我有一个非常特殊的问题,与春季启动中的百里香有关,使用 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>

但是我们怎样才能同时使用三个表呢?

我想我对代表我的问题的表格已经足够清楚了,我真的希望有人可以帮助我。提前致谢。

标签: javaspringjpathymeleaf

解决方案


创建一个代表 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>

推荐阅读