I would like to extend the requirements mentioned in the earlier post to support deletes. We have two data model object - Organization & Department sharing a one-to-many relationship. With the below mapping I am able to read the list of departments from the organization object. I have not added the cascade ALL property to restrict adding a department when creating an organization.
How should I modify the @OneToMany annotation (and possibly @ManyToOne) to restrict inserts of department but cascade the delete operation such that all associated departments are deleted when deleting an organization object?
@Entity
@Table(name="ORGANIZATIONS")
public class Organization{
@Id
@GeneratedValue
Private long id;
@Column(unique=true)
Private String name;
@OneToMany(mappedBy = "organization", fetch = FetchType.EAGER)
private List<Department> departments;
}
@Entity
@Table(name="DEPARTMENTS")
Public class Department{
@Id
@GeneratedValue
Private long id;
@Column(unique=true)
Private String name;
@ManyToOne(fetch = FetchType.EAGER)
private Organization organization;
}
The code to delete the organization is just a line
organizationRepository.deleteById(orgId);
The test case to validate this is as below
@RunWith(SpringJUnit4ClassRunner.class)
@DataJpaTest
@Transactional
public class OrganizationRepositoryTests {
@Autowired
private OrganizationRepository organizationRepository;
@Autowired
private DepartmentRepository departmentRepository;
@Test
public void testDeleteOrganization() {
final organization organization = organizationRepository.findByName(organizationName).get(); //precondition
Department d1 = new Department();
d1.setName("d1");
d1.setorganization(organization);
Department d2 = new Department();
d2.setName("d2");
d2.setorganization(organization);
departmentRepository.save(d1);
departmentRepository.save(d2);
// assertEquals(2, organizationRepository.getOne(organization.getId()).getDepartments().size()); //this assert is failing. For some reason organizations does not have a list of departments
organizationRepository.deleteById(organization.getId());
assertFalse(organizationRepository.findByName(organizationName).isPresent());
assertEquals(0, departmentRepository.findAll().size()); //no departments should be found
}
}