首页 > 解决方案 > 使用spring mvc处理thymeleaf中的一对多关系

问题描述

我有一个实体作为供应商,另一个实体作为地址,它们之间的关系是一对多形式的供应商到地址。

注意:我正在使用 JPA

我的供应商实体

public class Vendor {

 private Integer id;

  private String name;

  private List<Address> address;

 // getter and setters

}

地址类:

public class Address {

private Integer id;

private String addressline1;
private String addressline2;

//getter and setters 
}

现在我正在使用 Thymeleaf ,我有一个场景,我需要将地址动态添加到特定供应商的表单中。

如何使用 Spring mvc 中的 Thymeleaf 对供应商中的地址对象进行对象绑定?

标签: springjpathymeleaf

解决方案


呃,这很棘手,因为绑定到表单不能以动态方式工作。这意味着你不能做像@Viergelenker 建议事情并将每个地址对象绑定到他自己的形式。

您可以将单个地址对象添加到模型中,例如

model.addAttribute("address", addressObject); // Snippet for Model-object
modelAndView.addObject("address", addressObject); // Snippet for ModelAndView object

然后在你的模板中定义一个表单,如:

<form .... method=".." th:object="${address}">
  <input type="hidden" th:field="*{id}" >
  <input type="text" th:field="*{addressline1}" >
  <input type="text" th:field="*{addressline2}" >
</form>

不幸的是,不可能将数组或列表添加到模型中并将该集合中的每个对象绑定到他自己的形式:

/* The following code doesn't work */
<th:block th:each="address : ${addresses}">
    <form .... method=".." th:object="${address}">
      <input type="text" th:field="*{addressline1}" >
      ...
    </form>
</th:block>

或者

/* The following code doesn't work */
<th:block th:each="address, stat : ${addresses}">
    <form .... method=".." th:object="${addresses[__stat.index__]}">
      <input type="text" th:field="*{addressline1}" >
      ...
    </form>
</th:block>

您可以做的是不使用表单绑定,而只是从没有绑定的表单中发送一些名称-值对(仅使用名称和 th:value 属性,而不是表单中的 th:field 属性)到控制器,获取它们来自 HttpServletRequest 对象并创建/更新/删除地址对象...或将整个 Vendor 对象绑定到一个表单(注意使用 stat.index):

<form th:object="${vendor}">
    <input type="hidden" th:field="*{id}">
    <input type="hidden" th:field="*{name}"> // feel free to make that field editable
    <th:block th:each="addr, stat : *{address}">
      <input type="hidden" th:field="*{address[__${stat.index}__].id}">         
      <input type="text" th:field="*{address[__${stat.index}__].addressline1}">
      <input type="text" th:field="*{address[__${stat.index}__].addressline2}">
    </th:block>
 </form>

推荐阅读