2010-09-08 52 views
5

我與Spring MVC的工作,我想它綁定從數據庫中AA持久化對象,但我想不通我怎麼設置我的代碼,使綁定前調用數據庫。例如,我試圖更新「BenefitType」對象到數據庫中,但是,我想讓它變得fromthe數據庫中的對象,而不是創建一個新的,所以我沒有更新的所有字段。Spring MVC的3.0:如何綁定到一個持久化對象

@RequestMapping("/save") 
public String save(@ModelAttribute("item") BenefitType benefitType, BindingResult result) 
{ 
    ...check for errors 
    ...save, etc. 
} 

回答

4

所以我最終通過在類中用同名的@ModelAttribute註解方法來解決這個問題。 Spring在執行請求映射之前先建立模型:

@ModelAttribute("item") 
BenefitType getBenefitType(@RequestParam("id") String id) { 
    // return benefit type 
} 
0

雖然有可能是你的域模型是如此簡單,你可以綁定UI對象直接到數據模型對象,它更有可能的是事實並非如此,在這種情況下,我會強烈建議你設計一個類專門用於表單綁定,然後在它和控制器中的域對象之間進行轉換。

0

我有點困惑。我想你實際上是在談論更新工作流程?

需要兩個@RequestMappings,一個用於GET和一個POST:

@RequestMapping(value="/update/{id}", method=RequestMethod.GET) 
public String getSave(ModelMap model, @PathVariable Long id) 
{ 
    model.putAttribute("item", benefitDao.findById(id)); 
    return "view"; 
} 

然後在POST實際更新的領域。

在上面的示例中,您的@ModelAttribute應該已經用類似上述方法的方法填充,並且使用類似JSTL或Spring的tabglibs以及窗體支持對象綁定屬性。

您可能也想看看InitBinder這取決於你的使用情況。

3

有幾種選擇:

  • 在simpliest情況下,當你的對象只有簡單的屬性可以綁定其所有屬性的表單字段(hidden如果需要的話),之後得到一個完全綁定的對象提交。複雜屬性也可以使用PropertyEditor s綁定到表單域。

  • 您也可以使用會話將您的對象存儲在GETPOST請求之間。春季3個faciliates這種方法與@SessionAttributes註釋(從Petclinic sample):

    @Controller 
    @RequestMapping("/owners/*/pets/{petId}/edit") 
    @SessionAttributes("pet") // Specify attributes to be stored in the session  
    public class EditPetForm {  
        ... 
        @InitBinder 
        public void setAllowedFields(WebDataBinder dataBinder) { 
         // Disallow binding of sensitive fields - user can't override 
         // values from the session 
         dataBinder.setDisallowedFields("id"); 
        } 
        @RequestMapping(method = RequestMethod.GET) 
        public String setupForm(@PathVariable("petId") int petId, Model model) { 
         Pet pet = this.clinic.loadPet(petId); 
         model.addAttribute("pet", pet); // Put attribute into session 
         return "pets/form"; 
        } 
        @RequestMapping(method = { RequestMethod.PUT, RequestMethod.POST }) 
        public String processSubmit(@ModelAttribute("pet") Pet pet, 
         BindingResult result, SessionStatus status) { 
         new PetValidator().validate(pet, result); 
         if (result.hasErrors()) { 
          return "pets/form"; 
         } else { 
          this.clinic.storePet(pet); 
          // Clean the session attribute after successful submit 
          status.setComplete(); 
          return "redirect:/owners/" + pet.getOwner().getId(); 
         } 
        } 
    } 
    

    但是如果窗體的多個實例同時打開同一個會話這種方法可能會造成問題。

  • 所以,對於複雜的情況下,最可靠的方法是手動創建一個單獨的對象,用於存儲表單字段和合並來自該對象變成持久對象。

+0

我走下了這條路,但我真的不想使用會話。 – 2010-09-09 13:58:16

相關問題