我试图在表(OneToMany)中插入数据。我有两张桌子(好,分类)。Spring jpa hibernate insert OneToMany
@Entity
@Table(name = "goods")
public class Good implements Serializable {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id")
private Category category;
@JsonBackReference
public Category getCategory() {
return category;
}
//getters,setters is ommited
而另一:
@Entity
@Table(name = "category_of_products")
public class Category implements Serializable {
@OneToMany(mappedBy = "category", fetch = FetchType.LAZY, cascade = {
CascadeType.PERSIST, CascadeType.REFRESH })
private List<Good> goods;
@JsonManagedReference
public List<Good> getGoods() {
return goods;
}
//getter, setters ommited
比,在类别例如(ID = 1)中,i试图创建产品,其涉及到这一类。
@RequestMapping(value = CATEGORIES_ID_GOODS_ADD_DO, method = RequestMethod.POST)
public String addGoodAction(@PathVariable("id") Integer id,
@Valid Good good, BindingResult bindingResult, Model model) {
goodValidator.validate(good, bindingResult);
if (bindingResult.hasErrors()) {
return JspNamesUtil.GOODS_BY_CATEGORY;
} else {
RestTemplate restTemplate = new RestTemplate();
Category category = restTemplate.getForObject(
"http://localhost:8080/InternetShop/rest/category/" + id,
Category.class); //here i have category by id
// good.setCategory(category);
// goodManager.saveOrUpdate(good); doesn't insert anything
category.getGoods().add(good); //get all products from category and add new product
model.addAttribute("good", good);
categoryManager.saveOrUpdate(category); // doesn't insert anything
}
return JspNamesUtil.GOODS_BY_CATEGORY;
}
它们不会在我的表格中插入任何东西。
Hibernate: select category0_.id as id1_0_0_, category0_.name as name2_0_0_ from category_of_products category0_ where category0_.id=?
Hibernate: select goods0_.category_id as category7_0_0_, goods0_.id as id1_1_0_, goods0_.id as id1_1_1_, goods0_.category_id as category7_1_1_, goods0_.description as descript2_1_1_, goods0_.name as name3_1_1_, goods0_.price as price4_1_1_, goods0_.quantity as quantity5_1_1_, goods0_.short_description as short_de6_1_1_ from goods goods0_ where goods0_.category_id=?
方法坚持也是不工作(分离的实体除外)DAO
的例如
public Category saveOrUpdate(Category category) {
if (category != null) {
em.merge(category);
}
return category;
}
public void add(Category category) {
em.persist(category);
}
给我请一个提示,我做什么错?
我已经尝试过.. java.lang.IllegalStateException:相同的实体的多个表示[ua.internetshop.model.Good#1]是被合并。独立:[[email protected]];独立:[[email protected]] – oki
Theres至少有一次失败。 em.merge操作返回一个不同于传递参数的对象。所以你应该用category = em.merge(category);来代替它。但我认为这不会解决您的问题。 –
另外,我希望您很清楚,当您调用合并时,hibernate不会执行查询。这只会更新内部表示,它将在提交时持久保存到数据库。那么你是否100%肯定你在提交后检查了日志。并且提交被执行了。 –