| @Onetomany problems [message #895831] |
Mon, 16 July 2012 04:50  |
Maria Michael Messages: 1 Registered: July 2012 |
Junior Member |
|
|
Hello, this is the first time I post to this forum so I apologize for any mistakes i make.
Using Eclipse 2.3.0
Relationship One Mainform has many Students added to it (using JSF).
In order to make my relationship to work I ended up to the following setup which I do not understand the reason for the problems I had before finding this setup.
Relationship on the One side
@OneToMany(mappedBy = "mainform", fetch = FetchType.LAZY, cascade={CascadeType.ALL},orphanRemoval=true)
private List<Student> students;
Relationship on the Many Side
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "MAINFORM_ID", referencedColumnName = "MAINFORM_ID")
private MainForm mainform;
Problems I faced until I found the above correct (??) way.
1. In my JSF form I would add a new Student in the table (java list).
When I called em.merge(mainform) it would update the mainform and also create the new student in the related students table. When the user pressed Save in JSF againg, that is when the em.merge(mainform) was called again, without any other changes, the same Student was re-inserted in the table. By making the FetchType set to LAZY as shown above the problem was solved (I really don't understand why).
The main form entity was updated and the related Student was not re-inserted.
2. The next problem I faced was that when I entered a new StudentB in my students list and then em.merge(mainform), correctly it updated the database by adding the new studentB in the related table.
Then when i modified StudentA from the students list, on merge, it would update correctly StudentA in the database BUT it would recreate once again the StudentB.
The solution that I came up with was the addition of orphanRemoval =true as shown above.
Again I do not understand the reason why this behaviour.
Could someone explain me why it behaves like this.
Thank you very much.
|
|
|