JSP页面为forein关键参数

时间:2016-08-24 07:37:07

标签: hibernate jsp model foreign-key-relationship

我有2个表,Employee和City .Employee表有一个City(CityID)的外键。 我正在尝试从下拉列表中获取CityID值,但是从jsp页面返回的模型对于CityID始终具有空值;

员工实体

@Entity
@Table(name = "Employee", catalog = "DataGathering", schema = "dbo")
...
@JoinColumn(name = "CityID", referencedColumnName = "ID")
@ManyToOne
private City CityID;

城市实体

@Id
@Basic(optional = false)
@NotNull
@Column(name = "ID")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "CityName")
private String cityName;

@OneToMany(mappedBy = "CityID")
private Collection<Employee> EmployeeCollection1;

jsp表格

<td><form:select path="CityID" >
 <form:options items = "${cityList}" itemValue="id"itemLabel="cityName"/>
</form:select></td>

控制器

@RequestMapping(value="/new", method = RequestMethod.POST)
public String 
processRegistration(@ModelAttribute("tblEmployee")TblEmployee employee,
BindingResult result,
                Map<String, Object> model) {

    employeeService.create(employee);

    return "employee";
}

错误:

Cannot insert the value NULL into column 'CityID', table 
'DataGathering.dbo.Employee'; column does not allow nulls. INSERT fails.

1 个答案:

答案 0 :(得分:0)

我不确定,但一旦改变下面的代码

<td><form:select path="CityID" >
<form:options items = "${cityList}" itemValue="id"itemLabel="cityName"/>
</form:select></td>

如,

<td><form:select path="CityID" >
<c:forEach item="${cityList}" var="cityList">
   <options value= "${cityList.id}" itemLabel="cityName">${cityList.cityName}</option>
</c:forEach>
</form:select></td>

如果你没有在jsp页面中获得价值,那么将实体更改为

fetch = FetchType.EAGER