Adds removeEmployee method to Project

parent 9ce4f39a
......@@ -20,7 +20,7 @@ public class Project {
private String name;
@OneToMany(mappedBy="project", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
@OneToMany(mappedBy="project", cascade = {CascadeType.REMOVE, CascadeType.PERSIST}, orphanRemoval = true)
private Set<ProjectAssignment> projectAssignments = new HashSet<>();
public int getId() {
......@@ -54,9 +54,19 @@ public class Project {
// the ProjectAssignment is automatically persisted due to CascadeType.PERSIST
}
public void removeEmployee(Employee e) {
for (ProjectAssignment pa: this.projectAssignments) {
if (pa.getEmployee().equals(e)) {
// this will call internalRemoveProjectAssignment
pa.setProject(null);
// the project assignment will be also removed from the DB due to "orphanRemoval"
}
}
}
void internalRemoveProjectAssignment(ProjectAssignment projectAssignment) {
this.projectAssignments.remove(projectAssignment);
}
void internalAddProjectAssignment(ProjectAssignment projectAssignment) {
......
......@@ -69,6 +69,39 @@ public class ProjectsTest extends SQLBasedTest {
assertEquals(1, res.getInt("total"));
}
@Test
public void testRemoveEmployeeFromProject() throws SQLException {
// insert a project previously with JDBC
int projectId = insertAProject();
// insert an employee previously with JDBC
int employeeId = insertAnEmployee();
// assign the employee to the project (which should be removed due to CascadeType.REMOVE
// in Project.projectAssignments)
Statement statement = jdbcConnection.createStatement();
statement.executeUpdate("INSERT INTO ProjectAssignment(project_id, employee_id) values("+projectId+", "
+employeeId+")", Statement
.RETURN_GENERATED_KEYS);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Project p = new Projects(em).findById(projectId);
Employee e = new Employees(em).findById(employeeId);
p.removeEmployee(e);
em.getTransaction().commit();
// ensure that the project assignment does not exist
statement = jdbcConnection.createStatement();
ResultSet res = statement.executeQuery("SELECT COUNT(*) as total from ProjectAssignment where employee_id = " +
""+employeeId+" and project_id = "+projectId);
res.next();
assertEquals(0, res.getInt("total"));
}
@Test
public void testCreateProjectAssignment() throws SQLException {
// insert a project previously with JDBC
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment