我想将输入保存到Set界面。我有类Client.java:
@Table(name = "client")
public class Client {
@OneToOne(cascade = CascadeType.ALL)
private ShippingAddress shippingAddress;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Address> shippingAddresses = new HashSet<>();
}
Class ShippingAddress.java:
@Table(name = "address")
public class ShippingAddress {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
Long id;
String street;
String zip;
}
这是我的创作形式:
<form th:action="@{/add}" method="post" th:object="${client}">
<tr>
<td><input class="form-control" type="text" th:field="*{shippingAddress.street}"/></td>
<td><input class="form-control" type="text" th:field="*{shippingAddress.zip}"/></td>
</tr>
它工作正常,但我只能保存一个街道和一个拉链。我试图以这种方式改进它以便能够保存更多数据:
<form th:action="@{/add}" method="post" th:object="${client}">
<tr>
<td><input class="form-control" type="text" th:field="*{shippingAddress[0].street}"/></td>
<td><input class="form-control" type="text" th:field="*{shippingAddress[0].zip}"/></td>
</tr>
<tr>
<td><input class="form-control" type="text" th:field="*{shippingAddress[1].street}"/></td>
<td><input class="form-control" type="text" th:field="*{shippingAddress[1].zip}"/></td>
</tr>
但我得到的信息是:
无效的属性&shipping 39 [shippingAddress [0]&#39; bean类[model.Client]:在索引属性路径&shipping 39 [shippingAddress [0]&#39;中引用的属性既不是数组也不是List,也不是Set也不是Map;返回值为[ShippingAddress(id = null,street = null,zip = null,state = null,city = null,country = null)]
要为Set I添加值,应该使用add方法吗?但是如何用Thymeleaf来实现呢?
Controller中的方法(保存数据):
@Transactional
@RequestMapping(value = "add", method = RequestMethod.POST)
public String saveClient(@ModelAttribute Client client) {
clientRepository.save(client);
return "redirect:/";
}
Controller中的方法(打开创建表单)
@RequestMapping("/create")
public String newClient(Model model) {
model.addAttribute("client", new Client());
return "create";
}