当前位置: 首页 > 面试题库 >

当我尝试在数据库中插入数据时,“ org.hibernate.PersistentObjectException:分离的实体传递给持久化对象”

仉昂熙
2023-03-14
问题内容

我正在尝试将实体类持久化在数据库中,为此,我尝试了几种针对我的类的实现,但仍然面临错误(但存在不同的错误)。我的实体类现在像这样:

@Entity
@Table(name="pagina")
public class Pagina extends Entidade {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer Id;

    @Column(name = "nome", unique=true)
    private String nome;

    @Column(name = "titulo")
    private String titulo;

    @Column(name = "descricao")
    private String descricao;

    @OneToOne( cascade = {CascadeType.ALL}, fetch = FetchType.EAGER )
    @JoinColumn(name="parent_page")
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    private Pagina pagina;

    @OneToOne( cascade = {CascadeType.ALL}, fetch = FetchType.EAGER )
    @JoinColumn(name="parent_product")
    @Cascade(org.hibernate.annotations.CascadeType.ALL)
    private Produto produto;
}

在我的Dao类中,我为我的方法尝试了这两种实现persist(...)

@Transactional
public boolean persist(E transientInstance) {
    try {
        sessionFactory.getCurrentSession().persist(transientInstance);
        return true;
    } catch (RuntimeException e) {
        e.printStackTrace();
        return false;
    }
}

@Transactional
public boolean persist(E transientInstance) {
    try {
        sessionFactory.getCurrentSession().save(transientInstance);
        return true;
    } catch (RuntimeException e) {
        e.printStackTrace();
        return false;
    }
}

使用这两个选项时,如果我尝试保存没有属性Pagina或Produto的实体,则该实体将毫无问题地存储在数据库中。但是,如果我尝试使用此属性提交数据,则会遇到问题。

在第一个选项中,将org.hibernate.PersistentObjectException: detached entity passed to persist触发异常,在第二个选项中,数据将存储在数据库中,但是会出错,因为数据库中存储了没有值的额外行,并且插入了带有数据的行到那条线。

有人知道这里发生了什么吗?因为我不知道。

PS:

我有此视图在该表中插入数据:

<html lang="en">
  <head>
    <title>Pagina</title>
  </head>
  <body>
    <h1>Cadastro de Pagina</h1>


    <form id="command" role="form" class="form" action="Pagina/cadastra" method="post">

        <div class="panel panel-default">
            <div class="panel-heading">
            </div>
            <div class="panel-body">
                            <p>
                            <label for="nome" class="form-control">nome</label>
                            <input id="nome" name="nome" class="form-control" type="text" value=""/>
                            </p>

                            <p>
                            <label for="titulo" class="form-control">titulo</label>
                            <input id="titulo" name="titulo" class="form-control" type="text" value=""/>
                            </p>

                            <p>
                            <label for="descricao" class="form-control">descricao</label>
                            <textarea id="descricao" name="descricao" class="form-control"></textarea>
                            </p>

            </div>
        </div>

            <div class="panel panel-default">
                <div class="panel-heading">
                    Pagina
                </div>
                <div class="panel-body">

                        <input type="checkbox" name="Pagina.id" value="2">two<br>

                        <input type="checkbox" name="Pagina.id" value="1">one<br>

                </div>
            </div>

            <div class="panel panel-default">
                <div class="panel-heading">
                    Produto
                </div>
                <div class="panel-body">

                </div>
            </div>

        <p>
            <button type="submit" class="btn btn-lg btn-primary">Cadastrar</button>
        </p>

    </form>

    <div id="yes" class="alert alert-success" style="display: none;">
      <strong>Pronto!</strong> Solicita&ccedil;&atilde;o efetuada com sucesso.
    </div>

    <div id="not" class="alert alert-danger" style="display: none;">
      <strong>Erro!</strong> N&atilde;o foi possivel efetivar a sua solicita&ccedil;&atilde;o.
    </div>

  </body>
</html>

通过以下方法处理:

在控制器类中

@RequestMapping(value="cadastra", method=RequestMethod.POST)
@ResponseBody
public String cadastra(@ModelAttribute("object") E object, BindingResult result) {
    if(serv.cadastra(object))
        return "yes";
    else
        return "not";
}

在服务等级

@PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
@Transactional
public boolean cadastra(E e) {
    return dao.persist(e);
}

更新

当我尝试插入实体时发生的错误的stacktrace:

org.hibernate.PersistentObjectException: detached entity passed to persist: com.spring.loja.model.pagina.persistence.model.Pagina
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:139)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:801)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:794)
    at org.hibernate.engine.spi.CascadingActions$7.cascade(CascadingActions.java:314)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:350)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:293)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:161)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:118)
    at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:432)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:265)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
    at com.spring.loja.config.generic.persistence.Dao.persist(Dao.java:33)
    at com.spring.loja.config.generic.persistence.Dao$$FastClassBySpringCGLIB$$ddbbe880.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
    at com.spring.loja.model.pagina.persistence.PaginaHome$$EnhancerBySpringCGLIB$$7cc5cae5.persist(<generated>)
    at com.spring.loja.config.generic.service.service.cadastra(service.java:28)
    at com.spring.loja.config.generic.service.service$$FastClassBySpringCGLIB$$c92a3159.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:64)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
    at com.spring.loja.model.pagina.service.PaginaService$$EnhancerBySpringCGLIB$$71a378e.cadastra(<generated>)
    at com.spring.loja.config.generic.controller.controller.cadastra(controller.java:69)
    at com.spring.loja.config.generic.controller.controller$$FastClassBySpringCGLIB$$c8cc444b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:640)
    at com.spring.loja.model.pagina.controller.PaginaController$$EnhancerBySpringCGLIB$$8679f278_2.cadastra(<generated>)
    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:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    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.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.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    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.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.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Jul 13, 2014 9:07:48 PM org.hibernate.AssertionFailure <init>
ERROR: HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: null id in com.spring.loja.model.pagina.persistence.model.Pagina entry (don't flush the Session after an exception occurs)
Jul 13, 2014 9:07:48 PM org.apache.catalina.core.StandardWrapperValve invoke
Grave: Servlet.service() for servlet [jsp_dispatcher] in context with path [/loja] threw exception [Request processing failed; nested exception is org.hibernate.AssertionFailure: null id in com.spring.loja.model.pagina.persistence.model.Pagina entry (don't flush the Session after an exception occurs)] with root cause
org.hibernate.AssertionFailure: null id in com.spring.loja.model.pagina.persistence.model.Pagina entry (don't flush the Session after an exception occurs)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:77)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:192)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:152)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:231)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:102)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:55)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
    at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:555)
    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:478)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:272)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
    at com.spring.loja.model.pagina.service.PaginaService$$EnhancerBySpringCGLIB$$71a378e.cadastra(<generated>)
    at com.spring.loja.config.generic.controller.controller.cadastra(controller.java:69)
    at com.spring.loja.config.generic.controller.controller$$FastClassBySpringCGLIB$$c8cc444b.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:640)
    at com.spring.loja.model.pagina.controller.PaginaController$$EnhancerBySpringCGLIB$$8679f278_2.cadastra(<generated>)
    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:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.html" target="_blank">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.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.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    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.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.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

问题答案:

org.hibernate.PersistentObjectException: detached entity passed to persist

可以这样解释该错误(ouf,如何在不描述Hibernate / JPA的整个对象生命周期的情况下执行此操作?):

使用JPA / Hibernate,您可以将类定义为Entity。这意味着该类的对象可以由Hibernate管理,并因此存储在数据库中。

@Entity
public class Entity { /** ... */ }

当创建一个Entitynew Entity())类的新对象时,Hibernate对此一无所知。它不存储在数据库中,也不以任何方式受到Hibernate的控制。如果我们希望这些事情发生,我们需要persist对象(em.persist(entity))。当我们这样做时,对象状态存储在数据库中,而且对象本身也由Hibernate管理,这意味着Hibernate将跟踪对象的状态。另外,如果您已将Hibernate分配为生成ID,则将为该对象分配ID。

通过Hibernate从数据库加载对象时,该对象也将由Hibernate管理。一个新持久的对象或一个加载的对象都将具有一个ID,并且都将由Hibernate管理。但是,对象和Hibernate之间的连接可能会断开!发生这种情况时,对象变为detached。一个detached对象实际上只是一个entity具有其ID设置的类的对象,但是不受Hibernate管理。

当涉及到一个detached对象时,我们所拥有的选择不同于我们使用托管对象或新对象所具有的选择。与托管对象不同,detached不允许将对象传递给persist-method,因为它们已经具有ID,这意味着它们必须已经被持久保存了!当想要获取一个detached对象并对其进行管理时,merge-method是一种可以使用的方法。(http://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html#merge(T))
这会将合并的对象的状态与对应于对象ID的数据库状态合并。

merge使用新对象(不带id)进行调用将为其分配一个ID并保存,但要注意,它将对象作为参数传递时它不会做任何事情,而是会返回托管对象。

public Entity saveDetached(final Entity entity) {
    return em.merge(entity);
}

在您的情况下,解决方案将取决于一些因素,但是如果所引用的对象Pagina始终是数据库中已经存在的对象,那么我只需persist从中删除该操作的级联,并继续使用em.persist()merge有其缺点。)可能是新的,有时您还需要添加一些逻辑来确定是否要持久化(持久化拥有的对象之前)。(我也觉得可能工作加载PaginaProduto从数据库中,并将它们分配给新的Pagina面前persist。)

TL; DR

detached对象重新引入持久性上下文时,请使用merge-方法EntityManager,而不要使用persist-方法。



 类似资料:
  • 问题内容: 我已经成功用hibernate写了我的第一个主要的孩子例子。几天后,我再次使用它并升级了一些库。不知道我做了什么,但是我再也无法使它运行了。有人可以帮助我找出返回以下错误消息的代码中的错误吗: hibernate映射: 编辑: InvoiceManager.java 发票.java InvoiceItem.java 编辑: 从客户端发送的JSON对象: 编辑: 一些详细信息: 我试图通

  • 我在提交表单时遇到以下错误: org.hibernate.PersistentObjectException:传递给Persisted的分离实体:com.project.pmet.model.Account;嵌套异常为javax.persistence.persistenceException:org.hibernate.persistentObjectException:传递到persist的分

  • 问题内容: 我正在创建一个简单的应用程序,只需使用将一行插入到表中(如果表不存在,则创建它)。 我为它的一个可运行示例附加了一些代码。 这是我得到的异常和stacktrace: 这是我的代码: 主班: 和Person类: 这是我的persistence.xml文件 -----------------------编辑-------------------------- – 我只是将提供程序更改为Ec

  • 我有一个类通知,它包含一个对象MessengerData:

  • 这个网站上没有一个类似的问题能够解决我的问题。 错误:org.hibernate.persistentobjectexception:传递给persist:healthcheckapi.model.checks的分离实体 示例JSON健康对象: 请注意,这两个对象的ID都是自动生成的,我认为这是问题的一部分。

  • 问题内容: 结合使用JPA和Hibernate,运行以下代码时出现异常。第一次运行它时,一切正常,数据已插入数据库中。第二次,当应更新数据时,它失败: boutiqueDao.persist()只需调用EntityManager.persist()方法。 这是我的精品班: 最后,我的堆栈跟踪: 我正在Tomcat 7.0.32服务器上运行Java 7.0.11。 任何的想法? 问题答案: 用于全新