2016-04-21 43 views
0

我有一个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手动映射到客户,但我想避免这种情况。我想要模型映射器来做到这一点。

+1

我建议您将问题的标题改为“Thymeleaf从实体发布帖子中删除ID”。知道Hibernate的人无法帮助你,因为你已经诊断出这个问题。你想要一个知道spring-mvc/thymeleaf的人。 – Pace

回答

0

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

  1. 使属性隐藏在表单中,在调用后提交。
  2. 保存会话中的属性。

我更喜欢第二个选项去,因为隐藏字段可以在浏览器开发工具的形式提交前进行操作和属性也未考虑到需要不应该被送到查看,它看起来哈克。我将在会话中保存非ui属性,并在提交表单时将其恢复。