I am using Java8
, JPA
, Hibernate 5.2.1.Final
, Spring 4.3.1.RELEASE
and MySQL
.
Tables:
As you can see, I have a job
table joined to a location_job
tables, making use of the join table job_location
.
+---------+ +--------------+ +---------------+
| job | | job_location | | location_job |
+---------+ +--------------+ +---------------+
| ID | | JOB_ID | | ID |
| | | LOC_ID | | LAT |
| | | | | LONG |
+---------+ +--------------+ +---------------+
I am performing a delete on the job
table, and also want to delete the corresponding entries on the job_location
and location_job
tables.
Code:
Currently, my code deletes successfully from the job
and job_location
tables, but does not delete the corresponding entries from the location_job
table.
Job.java
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "job_location", joinColumns = {
@JoinColumn(name = "JOB_ID", referencedColumnName = "ID") }, inverseJoinColumns = {
@JoinColumn(name = "LOC_ID", referencedColumnName = "ID", unique = true) })
private Set<LocationJob> locations;
JobDaoImpl.java
@Repository("jobDao")
public class JobDaoImpl extends JpaDao<Long, Job> implements JobDao {
@Override
public boolean delete(Job job) {
Set<LocationJob> locations = job.getLocations();
if (locations != null) {
for (LocationJob location : locations) {
entityManager.remove(location);
}
job.getLocations().clear();
}
entityManager.remove(job);
return true;
}
}
JpaDao.java
public class JpaDao<I, T extends AbstractDomain<I>> {
protected Class<T> entityClass;
@PersistenceContext
protected EntityManager entityManager;
@SuppressWarnings("unchecked")
protected JpaDao() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[1];
}
protected void remove(T entity) {
entityManager.remove(entity);
}
}
Question
When I delete from the job
table, how can I make it also delete from the location_job
table?
Thank you.