Reputation: 3371
I am following the tutorial from here, and there is one part that I do not understand.
At 4. Run it – Case 1
session.beginTransaction(); Stock stock = new Stock(); stock.setStockCode("7052"); stock.setStockName("PADINI"); Category category1 = new Category("CONSUMER", "CONSUMER COMPANY"); session.save(category1); StockCategory stockCategory = new StockCategory(); stockCategory.setStock(stock); stockCategory.setCategory(category1); stockCategory.setCreatedDate(new Date()); //extra column stockCategory.setCreatedBy("system"); //extra column stock.getStockCategories().add(stockCategory); session.save(stock); session.getTransaction().commit();
The association between stock and category1 has been created while
stockCategory.setStock(stock); stockCategory.setCategory(category1);
Then, why do we still need
stock.getStockCategories().add(stockCategory);
Thanks!!
Upvotes: 0
Views: 149
Reputation: 2349
Strictly speaking the add is not necessary for hibernate to persist the objects. If you were to explicitly save the stock category then the relationship would be persisted. However you're only saving the stock object. Because of this the stock category needs to be in the collection so that hibernate can find it.
Notice the CascadeType.ALL on the categories collection. This means that on save, hibernate should look at the items in this collection and save them all. Because of this saving the stock is sufficient for hibernate to find and save the stock category and persist the relationship. If you did not add the item to the collection hibernate would not be able to find it so the relationship would not be saved unless you explicitly saved the StockCategory.
As mentioned in other answers, it's also generally considered good practice to keep the object graph consistent with the persistent state to avoid subtle bugs where what is populated is different at different times.
Upvotes: 1
Reputation: 691785
You don't abolutely need it to make the database happy, but not doing it makes the object graph inconsistent.
So if, for example, you return the stock with its categories as a result of this operation, and the client code (UI) iterates through the stock categories to display the new state of the system, the newly created stock will appear without any category, which is wrong.
Upvotes: 2