I have added CascadeType.All to the branches collection, and now its working. But i have another question now. It was not inserting value of branchID.
So i call branch.setCity() for both branch objects. And at the same time, i am also adding both branch objects in branches collection in city object and calling city.setBranches(). I think i am duplicating the code. Because on branch objects i am calling setCity(), and on city object i am calling setBranches(). How to solve this? I was expecting ejb wil handle it herself.
Just now i tried few things and now i am able to update/delete the city object. But if i want to delete a particular branch object from city.branches collection, how i will do it. I tried it but its not working.
Right now what i am doing is to first remove that branch object from the city.branches collection. Than i am calling bean's merge method. There is no error/exception, but that branch object is not deleted from database.
Table relationship is "each city has one to many branches"
Now, the problem is this that only city table is populated, while branch table is empty, and its not populated. Though i am setting the branch collection in city object.
Can you guys please tell me what is wrong in my code?
Yes. There is something wrong with the code. You are declaring the bidirectionality the wrong way.
Please change -
since you declared the bidirectionality as @OneToMany(mappedBy="city")
If you refer to the source code, mappedBy declared the field name of the variable in Branch object where bidirectionality exists.
In your client code, use the following
Of course, the basic premise in the application code is that the City Object already exists with the primary key of 1. If you do not want to set the City object manually in your branches, you could add the following code in your City
This callback method simply assigns the City object to the collection of Branches. In the EntityManager mechanism, after persisting City, it will call this method before persisting the collection of Branches.
Uy Jerwin Louise Vergara
Junior Developer / Research and Development at Incuventure Partners Corporation
Thanks a lot for pointing out the issue. But what if i want to remove a branch object from the city.branches collection. What need to be changed in the code. I tried, to remove on branch instance from the collection, and than i called merge method, but its not working. Can you tell you how to fix it?
It's exactly the same and completely different as this tiny ad: