2016-04-21 41 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屬性,並在提交表單時將其恢復。