hibernate - Use of Cascade in ManyToOne relation -


is appropriate use cascade in both sides of manytoone association in hibernate entities? make question more concrete, let 's assume has following related entities:

   public class department     {     public long id;      @onetomany(mappedby = "department", cascade=cascadetype.remove)     private set<employee> employees;     }      public class employee{      @generatedvalue(strategy=generatedvalue.identity)     public longempid;      @manytoone     public department department;     } 

in above relation department has many employees, hence rational force employees deleted when department deleted. right?

however, owner of relation employee. therefore question is, appropriate-correct choice ragarding put cascadetype.persist. choose 1 of 2 sides, according special needs or put on both sides well? if put on department side, following code save employees well, considering employee owner of relation?

employee e1 = new employee(); employee e2 = new employee(); department d = new department(); d.getemployees.add(e1); d.getemployees.add(e2); em.persist(d); 

i sure the opposite works if put cascadetype.persist on employee side.(saving employee save department well).

first of all, in code posted, employee not owner of association. if association bidirectional, , if onetomany association defined mappedby attribute:

@onetomany(mappedby = "department", cascade = cascadetype.remove) private set<employee> employees; 

(note made field private. public fields should never used).

regarding removal of department: in company, when department removed, employees not automatically fired. assigned department, or stay in company without being affected department, they're not deleted. understand application doesn't models real world, no, not rational force employees deleted when department deleted.

now, assuming mapping above, yes, can add persist cascade onetomany association. cascades , ownership orthogonal notions. if want persist() operation cascaded department employees (ie. if want create employees when creating department), add cascade. association saved, since owner side employee, employee.department field have correctly initialized, though.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -