Hibernate无法删除父实体 - 双向关系父/子

时间:2016-01-20 14:01:24

标签: java hibernate spring-mvc

我在删除项目中的父对象时遇到问题。 我使用相同的方法删除其他对象,但有时它确实有点挣扎。 通常我用HQL查询来解决这个问题,但这次也没有用。

我使用的数据库是一个oracle数据库。

先谢谢你的帮助,

卡斯帕

ApplicationProperty对象:

@Entity
@Table(name = "APPLICATION_PROPERTIES", uniqueConstraints = @UniqueConstraint(columnNames = { "NAME",
        "APPLICATION_ID" }) )
@SequenceGenerator(name = "APP_PROPERTIES_SEQ", initialValue = 1, allocationSize = 100)
public class ApplicationProperty extends DomainObject {

    private static final long serialVersionUID = -2441267205536610532L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "APP_PROPERTIES_SEQ")
    private Long id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "APPLICATION_ID", nullable = false)
    private ApplicationInfo application;

    @NotNull
    @NotBlank
    private String name;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval=true )
    @JoinColumn(name = "APP_PROPERTY_ID")
    @LazyCollection(LazyCollectionOption.FALSE)
    private List<EnvironmentProperty> environmentProperties;

    @Column(name = "REQUIRED")
    private Boolean required;

// Getters and setters

EnvironmentProperty对象:

@Entity
@Table(name = "ENVIRONMENT_PROPERTIES")
@SequenceGenerator(name = "ENVIRONMENT_PROPERTIES_SEQ", initialValue = 1, allocationSize = 100)
public class EnvironmentProperty extends DomainObject {

    private static final long serialVersionUID = -5469454706207348461L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ENVIRONMENT_PROPERTIES_SEQ")
    private Long id;

    @Column(name = "VALUE")
    private String value;

    @Column(name = "LAST_MODIFIED")
    private Date lastModified;

    @ManyToOne(cascade = CascadeType.MERGE)
    @JoinColumn(name = "ENVIRONMENT_ID", nullable = false)
    private Environment environment;

    @ManyToOne(cascade = CascadeType.DETACH)
    @JoinColumn(name = "APP_PROPERTY_ID", nullable = false)
    private ApplicationProperty applicationProperty;
// getters and setters

控制器:

@RequestMapping(value = { "/application/{applicationId}/edit" }, params = {
        "removeField" }, method = RequestMethod.POST)
public String removeRow(Model model,@ModelAttribute("app") ApplicationInfo application, HttpServletRequest req,
        @PathVariable("applicationId") Long applicationId) throws ApplicationNotFoundException {
    int propertyIndex = Integer.parseInt(req.getParameter("removeField"));

    applicationPropertyService.deleteProperty(application.getProperties().get(propertyIndex));

    List<Customer> customerList = customerService.getAllCustomers();
    model.addAttribute("app", application);
    model.addAttribute("customerList", customerList);
    return "application/edit";
}

从此处我们转到我只在我的DAO中调用此方法的服务:

@Transactional(propagation = Propagation.REQUIRED)
@Override
public void delete(T t) {
    if (!getEntityManager().contains(t)) {
        t = getEntityManager().merge(t);
    }
    getEntityManager().remove(t);
}

或者这种方法都失败了:

@Transactional
    public void deleteProperty(ApplicationProperty property) {
        try {
            System.out.println("DAO PROPERTY TO DELETE: " + property);
            Query query = entityManager.createQuery("DELETE FROM ApplicationProperty p where p.id=:id");
            query.setParameter("id", property.getId());
            query.executeUpdate();
        } catch (Exception e) {
            System.out.println(e);
            ;
        }
    }

以下是我得到的例外情况:

Hibernate: delete from APPLICATION_PROPERTIES where id=?
2016-01-20 14:45:09 WARN  SqlExceptionHelper:144 - SQL Error: 2292, SQLState: 23000
2016-01-20 14:45:09 ERROR SqlExceptionHelper:146 - ORA-02292: integrity constraint (DEPLOY.FK_96EUW5DGCLGY4Q5MEE9JTBQYR) violated - child record found

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
jan 20, 2016 2:45:09 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [/mds] threw exception [Request processing failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly] with root cause
javax.persistence.RollbackException: Transaction marked as rollbackOnly
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:72)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:521)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy44.deleteProperty(Unknown Source)
    at nl.ciber.deploy.metadata.controller.ApplicationsController.removeRow(ApplicationsController.java:198)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

0 个答案:

没有答案