Hieveryone, i have 2 Entity classes, called Category and Product which is oneToMany relationship.
when i add a new product with a given category into database, category side is not updated with new product. Thus categoryList holds still old products.
i am using JSF2.0 with JPA 2.
Product entity:
public class Product implements Serializable {
@ManyToOne
private Category category;
//getters::setters
Category entity:
public class Category implements Serializable {
@OneToMany(mappedBy = "category")
private List<Product> productList;
ProductController class:
public ProductController {
@EJB
private ProductService productService;
private Category category;
private Product product;
//getters::setters
//actionMethod called by JSFpage.
public String addProduct(){
product.setCategory(category);
productService.add(product);
return "productPage.xhtml";
}}
This way i can`t see any update on Category side.
So i have found a solution to this problem. I changed the code in ProductController as shown in below…
public ProductController {
@EJB
private ProductService productService;
@EJB
private CategoryService categoryService;
private Category category;
private Product product;
//getters::setters
//actionMethod called by JSFpage.
public String addProduct(){
product.setCategory(category);
productService.add(product);
// update category with new product
category.getProductList().add(product);
categoryService.update(category);
return "productPage.xhtml";
}}
This way category is updated BUT, i dont want CategoryService in my ProductController.t find right combination 🙂
How to implement this?
i have tried with Cascade.ALL/REFRESH... but i think i couldn
It’s the responsibility of the developer (you) to maintain the two sides of a bidirectional relationship inside a session. JPA will only take into account the side which owns the relationship to decide what has to be updated. The owning side is the side where there is no
mappedByattribute.So, in your example, setting the category to the product is sufficient for JPA to insert a new product in database and link it to the category (because product is the owning side). But the inverse relationship won’t be automatically updated by JPA. You must do it manually. If you discard your category object and reload it from the database, you’ll find the new product inside the category’s list of products.