我已经阅读了许多关于 spring-hibernate 关系的教程,但我对如何在我的情况下使用它们感到有点困惑......我的产品/类别实体定义如下:
产品
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private int id;
@Column
private int category;
.
.
.
类别
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private int id;
@NotEmpty
@Column
@Size (max = 25)
private String name;
.
.
.
所以,我想在产品列表页面中,在语音“类别”下会出现类别名称,在产品形式中会出现类别列表......在我的情况下,一个产品只适合一个类别,所以如果我是对的它应该是@ManyToOne,但我不知道如何实现它......在我的产品数据库中,我有 categoryId 字段,但如果我将类别实体字段标记为@OneToMany,它将不会存储到数据库中。 ..
编辑 我已经改变了(如建议的那样): Product.class
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private int id;
@NotEmpty
@Column
@Size (max = 25)
private String name;
@Column
@Size (max = 255)
private String description;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "category_id", nullable = false)
private Category category;
类别.class
@Entity
@Table(name = "categories")
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private int id;
@NotEmpty
@Column
@Size (max = 25)
private String name;
@Column
@Size (max = 255)
private String description;
//Here mappedBy indicates that the owner is in the other side
@OneToMany(fetch = FetchType.EAGER, mappedBy = "category", cascade = CascadeType.ALL)
private Set<Product> products = new HashSet<Product>();
控制器
@RequestMapping(value = "/add/", method = RequestMethod.POST)
public String addProduct(
@ModelAttribute(value = "product") @Valid Product product,
BindingResult result, ModelMap model, Category category) {
if (result.hasErrors()) {
return "forms/productForm";
}
try {
category.addProduct(product);
product.setCategory(category);
// Add product to db
productService.addProduct(product);
} catch (Exception e) {
log.error("/add/---" + e);
return "redirect:/product/deniedAction/?code=0";
}
return "redirect:/admin/product/";
}
我还在产品控制器上添加了一个@initbinder,以将数据从产品表单字符串转换为类别...但是现在当我保存产品时,它会自动保存一个类别而不是附加现有的选定类别...