JPA @manytomany unidirectional mapping

我的梦境 提交于 2019-12-06 14:58:38

Find it little bit hard to understand the question. I'm assuming you are looking for the externalsources to be removed when you remove the externaltask entity. I think for that you need to include REMOVE in your cascade settings or basically cascade={CascadeType.ALL}

EDIT: Think I found the answer to your situation. When the many to many is wired the PP creates an integrity constraint on the db (I'm thinking you are doing an auto gen of the schema from the entities).

In this case SOURCE_TASK table where the relationship between source and task is held, has a foreign key relationship towards SOURCE table. So when you try to remove something from SOURCE table the underlying db gives a sql exception. I was able to reproduce your issue.

Solution: What I did was I removed the foreign key constraint and I was able to remove the source entity fine.

As I originally stated for the TASK to SOURCE removal If you remove the TASK entity with Cascade.ALL it should remove the entries everywhere.

Update: I'm thinking there is something in the way you are dealing with equality among your SOURCE objects. The List.contains(o) will be true if at least one object that is 'equal' is found. The List.remove(o) will remove the first occurrence of an object that 'equals' o. So I bet there are multiple occurrences of 'equal' objects inside the list.

I add join fetch and problem solved.

public boolean deleteExternalDataStorage(Long sid) {
        EntityManager em = getEntityManager();
        EntityTransaction et = em.getTransaction();

        try {
            et.begin();
            ExternalDataStorage s = em.find(ExternalDataStorage.class, sid);            
            List<ExternalTask> tasks=(List<ExternalTask>) em.createQuery("SELECT t FROM ExternalTask t join fetch t.externalSources").getResultList();
           for(ExternalTask t:tasks) {
              if(t.getExternalSources().contains(s)){
                      t.getExternalSources().remove(s);
                  if(t.getExternalSources().isEmpty()){
                      em.remove(t);
                  }
               }
           }       
            em.remove(s);
            et.commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
             if (et.isActive()) {
                et.rollback();
            }

        } finally {

        }
        return false;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!