0

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.

Richard
  • 8,193
  • 28
  • 107
  • 228

1 Answers1

0

I found the answer here.

I needed to add orphanRemoval=true:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval=true)
@JoinTable(name = "job_location", joinColumns = {
        @JoinColumn(name = "JOB_ID", referencedColumnName = "ID") }, inverseJoinColumns = {
                @JoinColumn(name = "LOC_ID", referencedColumnName = "ID", unique = true) })
private Set<LocationJob> locations;
Community
  • 1
  • 1
Richard
  • 8,193
  • 28
  • 107
  • 228