Thymeleaf 从 Spring-mvc 中的帖子中剥离实体 id



我有一个 customerDto,它有一个子对象 customerAddress。我只想更新客户Dto(包括客户地址)。我遇到的问题是休眠正在为客户的每个更新查询插入一个新的客户地址行。这是因为thymleaf视图没有返回客户地址ID(主键)。

@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);

因为我正在使用模型映射器在我的服务中从客户D到客户进行映射。客户实体对象最终具有空的客户地址 id,这会导致数据库中出现一个新行。

那么 - 客户地址对象如何维护其属性从视图返回到控制器?我的做法正确吗?我可以手动将客户D映射到客户,但我想避免这种情况。我希望模型映射器执行此操作。

感谢 Pace 上面的评论,这让我重新思考问题并再次调试。问题是,如果请求后弹簧控制器中不存在实体属性(不仅仅是 id),则显然不知道要绑定到实体的内容。在我看来,有两种可能的解决方案。

  1. 将属性隐藏在将在呼叫后提交的表单中。
  2. 在会话中保存属性。

我更喜欢使用第二个选项,因为在表单提交之前可以在浏览器开发工具中操作隐藏字段,并且不应将视图中不需要的属性发送到查看中,它看起来很hack。我将在会话中保存非 ui 属性,并在提交表单时检索它们。

最新更新