Когда я пытаюсь удалить ExternalDataStorage. Этот запрос выдает исключение нарушения ограничения с именем ограничения null. ExternalDataStorage не имеет сопоставления отношений. Сначала проверьте ExternalTasks, которые содержат ExternalDataStorage (который будет удален) в списке ExternalSask 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 реализует Сериализуемый {
@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;
_ EDIT _ __ _ __ _ __ _ __ _ __ _ ___
Я немного изменил запрос для удаления регистра, но проблема все еще существует
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)
в org.postgresql.core.v3.QueryExecutorImpl.processResults (QueryExecutorImpl.java:1328)
в 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 (собственный метод)
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)
в 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)
в 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)
в org.apache.catalina.core.StandardContextValve.invoke (StandardContextValve.java:191)
в org.apache.catalina.core.StandardHostValve.invoke (StandardHostValve.java:127)
в 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 delete from ExternalSource, где EXID = 6 был прерван. Вызовите getNextException, чтобы увидеть причину.
at org.postgresql.jdbc2.AbstractJdbc2Statement $ BatchResultHandler.handleError (AbstractJdbc2Statement.java:2537)
в org.postgresql.core.v3.QueryExecutorImpl.processResults (QueryExecutorImpl.java:1328)
в 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;