我有一個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