简体   繁体   中英

Spring jpa hibernate insert OneToMany

I'm trying to to insert data in table (OneToMany). I have two tables(Good, Category).

    @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

And another:

    @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

Than, in category for example(id=1), i trying to create product which relate to this category.

@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;
        }

and they don't insert anything in my table.

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=?

method persist is also dont work(Detach entity exception)

example of DAO

public Category saveOrUpdate(Category category) {
        if (category != null) {
            em.merge(category);
        }
        return category;
        }
        public void add(Category category) {
           em.persist(category);
        }

give me please a hint, what i do wrong?

This may be a test solution that can evolve depending on your tests:

There is two things to do:

  1. Change your CascadeType.PERSIST to CascadeType.CASCADE_ALL To not have to deal with cascade problems (you can rollback this, once this solution works).
  2. Add an addGood(Good good) in Category class and add (if it does not already exists ) a setter for Category in Good class. You have to manage a bi-directionnal relationship wiring Good to Category and wiring back Category to Good .

The addGood method will be like this :

public void addGood(Good good) {
 this.goods.add(good);
 good.setCategory(this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM