【问题标题】:multiple models of the same length iterating simultaneously多个相同长度的模型同时迭代
【发布时间】:2021-08-29 23:22:19
【问题描述】:

我有一个非常特殊的问题,与 Spring Boot 中的 thymeleaf 相关,使用 Java Persitence API (JPA)。

我有三个表(A、B、C),因此模型,它们看起来像这样:

答:

@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
}

按照设计,这三个表格将具有相同数量的内容。

表格的行是这样的:

答:

帮助内容

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>

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

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

【问题讨论】:

    标签: java spring jpa thymeleaf


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 2019-02-23
      • 1970-01-01
      • 2017-10-15
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多