I have an Employee class which has a unidirectional many to many relationship with Technology class. When I add technologies to Employee and merge the employee, the records are added to the join table.
But, when I try to delete the technologies by merging the employee, the changes do not reflect on the database.
Employee.class
@Entity
@Table(name = "EMPLOYEES")
public class Employee implements Serializable {
@JoinTable(name = "EMPLOYEES_TECHNOLOGIES",
joinColumns =
@JoinColumn(name = "EMP_USERNAME", referencedColumnName = "USERNAME", table = "EMPLOYEES"),
inverseJoinColumns =
@JoinColumn(name = "TEC_ID", referencedColumnName = "ID", table = "TECHNOLOGIES"))
private List<Technology> technologies;
EmployeeEAOImpl.class
@Stateless(name = "EmployeeEAO")
public class EmployeeEAOImpl implements EmployeeEAO {
@PersistenceContext(unitName = "ManagedITest")
private EntityManager em;
@Override
public void update(Employee employee) {
if (employee != null) {
try {
em.merge(employee);
em.flush();
} catch (RuntimeException ex) {
em.clear();
throw ex;
}
}
}
Seems pretty standard to me. I checked the generated queries and when I create/update an Employee with technologies I get this:
INSERT INTO EMPLOYEES_TECHNOLOGIES (TEC_ID, EMP_USERNAME) VALUES (?, ?)
bind => [99, TEST]
But when I delete technologies from Employee and merge, I get either this wrong query:
DELETE FROM EMPLOYEES_TECHNOLOGIES WHERE ((TEC_ID = ?) AND (EMP_USERNAME = ?))
bind => [99, null]
Or I get an exception:
Exception Description: The attribute [id] of class [be.brail.entities.Employee] is mapped to a primary key column in the database. Updates are not allowed.
This makes me think that the employee is getting created since I’m not altering the ID, so the exception is thrown because the employee with that particular id already exists. At least, that’s what I think.
Why the username parameter in the DELETE query is null, I don’t know. But I’d like to 🙂
Thanks in advance.
It appears that using only entity id’s on the join table fixed it. Not sure why there can’t be references to foreign keys, but it works! It’s a better design anyways since id’s cannot be altered.