JPA @manytomany单向映射

时间:2011-06-09 19:39:41

标签: hibernate jpa many-to-many

当我尝试删除ExternalDataStorage时此查询抛出一个约束违规异常,约束名为null .ExternalDataStorage上没有关系映射。查询首先检查哪些包含ExternalDataStorage(将被删除)的ExternalTask​​s在ExternalTask​​的externalsources List和从列表中删除,如果列表为空,则删除externaltask,最后删除ExternalDataStorage实体(目标实体)。

      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 ").getResultList();
        for (ExternalTask t : tasks) {
            if (t.getExternalSources().contains(s)) {
                t.getExternalSources().remove(s);
                if (t.getExternalSources().isEmpty()) {
                    em.remove(t);
                } else {
                    t = em.merge(t);
                }
            }
        }
        em.remove(s);
        et.commit();
        return true;
    } catch (Exception e) {
        e.printStackTrace();


    } finally {
        if (et.isActive()) {
            et.rollback();
        }
    }
    return false;
}

@Entity 公共类ExternalTask​​实现Serializable {

@ManyToMany(cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
@JoinTable(name = "ExternalTask_ExternalSource", joinColumns = @JoinColumn(name = "TID"), inverseJoinColumns = @JoinColumn(name = "EXID"))
private  List<ExternalDataStorage> externalSources =new ArrayList<ExternalDataStorage>();


@ManyToMany(cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
@JoinTable(name = "ExternalTask_Archive", joinColumns = @JoinColumn(name = "TID"), inverseJoinColumns = @JoinColumn(name = "AID"))
protected  List<Archive> archives=new ArrayList<Archive>();


@ManyToOne
private User  ownerUser;

_ 修改 _ __ _ < / EM> __ _ __ _ __ _ __ _ ___

我为删除案例稍微更改了查询但问题仍然存在

  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 ").getResultList();
           for(ExternalTask t:tasks) {
              if(t.getExternalSources().contains(s)){
                 t.getExternalSources().remove(s);
                  t= em.merge(t);
                  if(t.getExternalSources().isEmpty()){
                      em.remove(t);
                  }
               }
           }                 
            em.remove(s);
            et.commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();


        } finally {
            if (et.isActive()) {
                et.rollback();
            }
        }
        return false;
    }

这是例外

**377249 [http-8080-2] WARN  org.hibernate.util.JDBCExceptionReporter  - SQL Error: 0, SQLState: null
377249 [http-8080-2] ERROR org.hibernate.util.JDBCExceptionReporter  - Batch entry 0 delete from ExternalSource where EXID=6 was aborted.  Call getNextException to see the cause.
377249 [http-8080-2] WARN  org.hibernate.util.JDBCExceptionReporter  - SQL Error: 0, SQLState: 23503
377249 [http-8080-2] ERROR org.hibernate.util.JDBCExceptionReporter  - ERROR: update or delete on table "externalsource" violates foreign key constraint "fk755287f526733b01" on table "externaltask_externalsource"
  Detail: Key (exid)=(6) is still referenced from table "externaltask_externalsource".
377250 [http-8080-2] ERROR org.hibernate.event.def.AbstractFlushingEventListener  - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
        at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:144)
        at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
    at com.endersys.itap.ui.module.storage.StorageManager.deleteExternalDataStorage(StorageManager.java:351)
    at com.endersys.itap.ui.module.storage.ExternalDataStorageEditorBean.delete(ExternalDataStorageEditorBean.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:172)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
    at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:78)
    at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:57)
    at javax.faces.component.UICommand.broadcast(UICommand.java:127)
    at org.ajax4jsf.component.AjaxActionComponent.broadcast(AjaxActionComponent.java:55)
    at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:329)
    at org.ajax4jsf.component.AjaxViewRoot.broadcastEventsForPhase(AjaxViewRoot.java:304)
    at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:261)
    at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:474)
    at org.apache.my**faces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:32)
    at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:103)
    at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:76)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:183)
    at org.apache.myfaces.webapp.MyFacesServlet.service(MyFacesServlet.java:103)
    at com.endersys.itap.ui.MyFacesServletWrapper.service(MyFacesServletWrapper.java:34)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:341)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206)
    at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
    at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
    at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.endersys.itap.ui.MenuFilter.doFilter(MenuFilter.java:169)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:636)

引起:java.sql.BatchUpdateException:批处理条目0从ExternalSource删除,其中EXID = 6已中止。调用getNextException以查看原因。         at org.postgresql.jdbc2.AbstractJdbc2Statement $ BatchResultHandler.handleError(AbstractJdbc2Statement.java:2537)         at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1328)         at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:351)         at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2674)         在org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)         在org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)         ......还有55个 javax.persistence.RollbackException:提交事务时出错         在org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:71)         在com.endersys.itap.ui.module.storage.StorageManager.deleteExternalDataStorage(StorageManager.java:351)         在com.endersys.itap.ui.module.storage.ExternalDataStorageEditorBean.delete(ExternalDataStorageEditorBean.java:73)         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)         在java.lang.reflect.Method.invoke(Method.java:616)         在org.apache.el.parser.AstValue.invoke(AstValue.java:172)         at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)         在com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)         在javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:78)         at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:57)         在javax.faces.component.UICommand.broadcast(UICommand.java:127)         在org.ajax4jsf.component.AjaxActionComponent.broadcast(AjaxActionComponent.java:55)         在org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:329)         在org.ajax4jsf.component.AjaxViewRoot.broadcastEventsForPhase(AjaxViewRoot.java:304)         在org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:261)         在org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:474)         在org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:32)         在org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:103)         在org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:76)         在javax.faces.webapp.FacesServlet.service(FacesServlet.java:183)         在org.apache.myfaces.webapp.MyFacesServlet.service(MyFacesServlet.java:103)         在com.endersys.itap.ui.MyFacesServletWrapper.service(MyFacesServletWrapper.java:34)         在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)         在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)         在org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:341)         在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)         在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)         在org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206)         在org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)         在org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)         在org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)         在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)         在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)         在com.endersys.itap.ui.MenuFilter.doFilter(MenuFilter.java:169)         在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)         在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)         在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)         在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)         在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)         在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)         在org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)         在org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler.process(Http11Protocol.java:588)         在org.apache.tomcat.util.net.JIoEndpoint $ Worker.run(JIoEndpoint.java:489)         在java.lang.Thread.run(Thread.java:636) 引起:org.hibernate.exception.ConstraintViolationException:无法执行JDBC批量更新         在org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)         在org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)         在org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)         在org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)         在org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:144)         在org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)         在org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)         在org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)         在org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)         在org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)         在org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)         ......还有47个 引起:java.sql.BatchUpdateException:批处理条目0从ExternalSource删除,其中EXID = 6被中止。调用getNextException以查看原因。         at org.postgresql.jdbc2.AbstractJdbc2Statement $ BatchResultHandler.handleError(AbstractJdbc2Statement.java:2537)         at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1328)         at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:351)         at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2674)         在org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)         在org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)         ......还有55个

And this is constraint on table



ALTER TABLE externaltask_externalsource
  ADD CONSTRAINT fk755287f526733b01 FOREIGN KEY (exid)
      REFERENCES externalsource (exid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION;

2 个答案:

答案 0 :(得分:1)

发现它有点难以理解这个问题。我假设您正在寻找在删除externaltask实体时要删除的externalsources。我认为你需要在级联设置中包含REMOVE或者基本上是cascade = {CascadeType.ALL}

编辑: 想想我找到了你的情况的答案。当多对多线路连接时,PP会在db上创建一个完整性约束(我认为你正在从实体中做一个模式的自动生成)。

在这种情况下,源和任务之间的关系所在的SOURCE_TASK表与SOURCE表具有外键关系。因此,当您尝试从SOURCE表中删除某些内容时,底层数据库会提供一个sql异常。我能够重现你的问题。

解决方案: 我做的是删除了外键约束,我能够删除源实体。

正如我最初所说的TASK去除SOURCE 如果您使用Cascade.ALL删除TASK实体,它应该删除所有条目。

更新:我认为你处理SOURCE对象之间的平等有一些方法。如果找到至少一个“相等”的对象,则List.contains(o)将为true。 List.remove(o)将删除第一次出现'等于'o的对象。所以我敢打赌,列表中会出现多次“相等”的对象。

答案 1 :(得分:0)

我添加了连接提取并解决了问题。

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;
    }