我有一个customerDto,它有一个子对象customerAddress。我只是想更新customerDto(包括customerAddress)。 我遇到的问题是hibernate为客户的每个更新查询插入一个新的customerAddress行。这是因为thymleaf视图没有返回customerAddress标识(主键)。Thymeleaf从实体上从实体上发帖于Spring-mvc
@RequestMapping(value = "findcustomer")
public String findCustomer(@ModelAttribute("customerDto") CustomerDto customerDto, Model model) {
CustomerDto customerDto = service.search(customerDto);
model.addAttribute("customerDto", customerDto); // I can see customerAddress id sent to view here.
return "mypage";
}
我的空间形态:
<form method="post" th:action="@{updatecustomer}" th:object="${customerDto}">
<label>Email: </label><input type="text" th:field="*{email}" />
<label>Address Line 1</label><input type="text" th:field="*{customerAddress.lineOne}"/>
<input type="submit" />
</form>
@RequestMapping(value = "updatecustomer")
public String updateCus(@ModelAttribute("customerDto") CustomerDto customerDto, Model model){
// the customerAddress id within the customerDto is null here
customerDto = service.updateCustomer(customerDto);
model.addAttribute("savedCus", customerDto);
return "updatedCustomerPage"
}
服务:
Customer customer = repository.findCustomer(customerDto.getNumber());
modelMapper.map(customerDto, customer);
repository.saveAndFlush(customer);
由于我使用ModelMapper映射来自customerDto客户在我的服务。客户实体对象最终具有空的customerAddress id,从而导致数据库中出现新行。
所以 - customerAddress对象如何保持从查看回控制器的属性?我的方法是否正确?我可以从customerDto手动映射到客户,但我想避免这种情况。我想要模型映射器来做到这一点。
我建议您将问题的标题改为“Thymeleaf从实体发布帖子中删除ID”。知道Hibernate的人无法帮助你,因为你已经诊断出这个问题。你想要一个知道spring-mvc/thymeleaf的人。 – Pace