Mike Cheung wrote:Okay so you have similar annotations defined in the entity class. The following bit must be something you added in addition to the setters and getters generated automatically.
So you are handling the relationship from both ends also.
Your job.addRecord(rec); is similar to my emp.getPHONEID().add(ph);
Your rec.setJob(job); is similar to my ph.setEMPLOYEEID(emp);
In other words, I guess we have verified in both my and your case the following:
1) If persisting an object on the Many side (ie Phone for me and Record for you), we don't need to add any special functions. The generated setter is able to handle it.
Pretty much.
But your existing One-side onject will not have the new Many-side object in its collection until you refresh it.
Mike Cheung wrote:
2) If persisting an object on the One side (ie Employee for me and Job for you), we need to add a special function (ie addRecord in your case) on top of the generated getters and setters. This special function needs to manage relationships from both ends.
Yep. But if the CASCADE is assigned to the One-side you get the advantage of persisting the whole thing in one go.
This may or may not be an advantage in your particular case.
As with most things codey there isn't a one-size-fits-all.
Mike Cheung wrote:
3) The Collection isn't persisted into the database. In your case, you will have a FK on the Records table pointing to a row on the Job table. But I don't believe you have any FKs on the Job table pointing to any rows on your Records table. This means the job.addRecord(rec); line can be commented out and you'll have the same result in the database.
That's the difference between relational and object. In my mind on the One-side the Collection is a representation of the relationship given by the FK on the other table. So the Collection is persisted in the only way it can be.
Mike Cheung wrote:
Can you confirm by in fact commenting out the following line and see if you have the same result in your database as if it's not commented out?
job.addRecord(rec);
It won't persist the Records because I call persist (well, merge I think) on the Job.
Since the Job does not have the Records in its List<> then the Records will not be persisted as Hibernate knows nothing about them.
No point me commenting out the code.