2017-06-18 42 views
0

我想保存一個窗體,在選擇標記中有一個外鍵,但它總是爲空。 !我不能保存外鍵在春天mvc窗體選擇標記

類用戶:

@Entity 
public class User implements Serializable{ 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long UserCode; 
    private String Lastname; 
    private String Firstname; 
    private String Adress; 
    @ManyToOne 
    @JoinColumn(name="CityCode") 
    private City CityCode; 
    private String phone; 
    private String mail; 
    private int newsletter; 

控制器:

@RequestMapping(value = "/add", method = RequestMethod.POST) 
     public String add(@ModelAttribute("userModel") User user,BindingResult bindingResult, Model model) {  
      user.setCreator("admin"); 
      user.setDateCreation(new Date()); 
      user.setDateChange(new Date()); 

      model.addAttribute("user", new User()); 
      metier.AddUser(user); 

      return "redirect:/user"; 
     } 

代碼的html:

<div class="form-group"> 
<label for="city" class="control-label col-lg-2">Ville</label> 
    <div class="col-lg-4"> 
    <f:select path="CityCode" class="control-label col-lg-12"> 
     <c:forEach items="${states}" var="state"> 
      <option value="${state.cityCode }">${state.name }</option>             
     </c:forEach> 
    </f:select> 
</div> 

我不能救市代碼表用戶

回答

0

我想你錯過的CascadeType :

@ManyToOne(cascade = CascadeType.ALL)

詳情這裏:https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-many-to-one-using-annotations-1.html

+0

我有此錯誤:在對象的usermodel'上字段 'CityCode' 字段錯誤:拒絕值[1];我不能保存類型城市citycode中的值1! –

+0

您確定value =「$ {state.cityCode}」是一個City對象嗎? – Padi

+0

value =「$ {state}」是一個City對象嗎?如果是,請嘗試更改value =「$ {state}」在保存用戶之前,您應該在CityCode字段中擁有一個有效的&持久對象City。我認爲你對你的註解感到困惑......所以一個City對象應該有一個cityCode(以及一個cityName,county等等),並且在你的c:forEach選項值中你傳遞了cityCode(這只是一個字段物體) – Padi