我試圖在表(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%肯定你在提交後檢查了日誌。並且提交被執行了。 –