【发布时间】:2018-01-24 00:46:18
【问题描述】:
我是 Hibernate/JPA 的新手,我正在尝试使用 hibernate 实体类获取表单参数。直到我尝试使用与其他类有关系的实体类获取参数时,它才出现问题。例如;
控制器:
@RequestMapping(value = "/addProduct", method = RequestMethod.POST)
public String addProduct(Model model, Product product) {
databaseService.insert(product);
return "redirect:/products";
}
实体类:
@Entity
@Table(name = "products")
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private String id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id")
private Category category;
@Column(name = "name")
private String name;
@Column(name = "price")
private String price;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
分类类:
@Entity
@Table(name = "categories")
public class Category implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private String id;
@Column(name = "name")
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
程序无法设置“类别”。因为类别不是 int、string 之类的类型。我意识到了这个问题。但我找不到使用实体类映射参数的解决方案。有什么办法可以解决这个问题。或者我应该使用@RequestParam 来一一获取参数,而不是使用实体类映射参数。
更新
我只是在我的 .jsp 页面中将 category 更改为 category.id,它解决了我的问题。
旧代码
<form>
...
<select class="form-control" name="category">
<c:if test="${not empty categoryList}">
<c:forEach var="item" items="${categoryList}">
<option value="${item.getId()}">${item.getName()}</option>
</c:forEach>
</c:if>
</select>
</form>
新代码
<form>
...
<select class="form-control" name="category.id">
<c:if test="${not empty categoryList}">
<c:forEach var="item" items="${categoryList}">
<option value="${item.getId()}">${item.getName()}</option>
</c:forEach>
</c:if>
</select>
</form>
【问题讨论】:
-
您还需要在 Category 类中的字段上添加注释。你能把Category chas的内容贴在这里吗?
-
我更新了帖子。可以看到分类内容。
-
在 post 方法中,您可以从模型中检索反序列化的任何参数。
-
您没有从 Category 到实体类的反向映射(One 到 Man7)。您可能还需要添加反向属性。
标签: java spring hibernate spring-mvc jpa