title: Unable to save entity in database when field mapping a foreign key is null
body: <p>In my current spring project, when I try insert in the database an entity which have as atribute a foreign key mapping, like that one:</p>
  
  <pre><code>@Entity
  @Table(name="pagina")
  public class Pagina {
  
      @Id
      @Column(name = "id")
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      private Integer id;
  
      @Column(name = "nome", length=32, nullable=false, unique=true)
      @Order(value=1)
      private String nome;
  
      @Column(name = "titulo", length=32, nullable=false)
      @Order(value=2)
      private String titulo;
  
      @Column(name = "descricao", length=65535)
      @Order(value=4)
      private String descricao;
  
      @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
      @JoinColumn(name="parent")
      @Order(value=5)
      private Parent parent;
  }
  </code></pre>
  
  <p>I am getting this error:</p>
  
  <pre><code>Grave: Servlet.service() for servlet [jsp_dispatcher] in context with path [/loja] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : com.spring.loja.model.pagina.persistence.model.Pagina.nome; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : com.spring.loja.model.pagina.persistence.model.Pagina.nome] with root cause
  org.hibernate.PropertyValueException: not-null property references a null or transient value : com.spring.loja.model.pagina.persistence.model.Pagina.nome
      at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:106)
      at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready(AbstractEntityInsertAction.java:132)
      at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:86)
      at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
      at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
      at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
      at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
      at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
      at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
      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.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.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:32)
      at com.spring.loja.config.generic.persistence.Dao$$FastClassBySpringCGLIB$$ddbbe880.invoke(&lt;generated&gt;)
      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$$c9fd6097.persist(&lt;generated&gt;)
      at com.spring.loja.config.generic.service.service.cadastra(service.java:45)
      at com.spring.loja.config.generic.service.service$$FastClassBySpringCGLIB$$c92a3159.invoke(&lt;generated&gt;)
      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$$a12f460d.cadastra(&lt;generated&gt;)
      at com.spring.loja.config.generic.controller.controller.cadastra(controller.java:42)
      at com.spring.loja.config.generic.controller.controller$$FastClassBySpringCGLIB$$c8cc444b.invoke(&lt;generated&gt;)
      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$$34bc66ed_2.cadastra(&lt;generated&gt;)
      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:749)
      at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
      at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
      at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
      at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
      at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
      at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
      at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
      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.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:108)
      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:108)
      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: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)
  </code></pre>
  
  <p>Anyone can tell me what I can do to save the data in this case? When the value for <code>parent</code> is null, the application should store the record in the database with a blank value for the foreign key, and not try save a empty entity.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>this entity persistence is handled by this methods:</p>
  
  <p><em>controller</em></p>
  
  <pre><code>@RequestMapping(value="cadastra")
  @PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
  public String cadastra(Model model) {
          model.addAttribute("command", this.entityClass.newInstance());
          model.addAttribute("entity", this.getName());
          model.addAttribute("map", serv.getAtributos());
          model.addAttribute("value", serv.getListaAtributos());
          return "private/cadastrar";
  }
  </code></pre>
  
  <p><em>html form</em></p>
  
  <pre><code>  &lt;form id="command" class="form" action="/loja/Pagina/cadastra" method="POST" enctype="multipart/form-data"&gt;
            &lt;div class="row"&gt;
                &lt;div class="col-md-3"&gt;&lt;/div&gt;
                &lt;div class="col-md-6"&gt;
  
                &lt;/div&gt;
                &lt;div class="col-md-3"&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="row"&gt;
                &lt;div class="col-md-3"&gt;
                    &lt;h3&gt;&lt;label for="nome" class="label label-default"&gt;nome&lt;/label&gt;&lt;/h3&gt;
                &lt;/div&gt;
                &lt;div class="col-md-6"&gt;
                    &lt;input id="nome" name="nome" class="form-control" type="text" value=""/&gt;
                &lt;/div&gt;
                &lt;div class="col-md-3"&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="row"&gt;
                &lt;div class="col-md-3"&gt;
                    &lt;h3&gt;&lt;label for="titulo" class="label label-default"&gt;titulo&lt;/label&gt;&lt;/h3&gt;
                &lt;/div&gt;
                &lt;div class="col-md-6"&gt;
                    &lt;input id="titulo" name="titulo" class="form-control" type="text" value=""/&gt;
                &lt;/div&gt;
                &lt;div class="col-md-3"&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="row"&gt;
                &lt;div class="col-md-3"&gt;
                    &lt;h3&gt;&lt;label for="descricao" class="label label-default"&gt;descricao&lt;/label&gt;&lt;/h3&gt;
                &lt;/div&gt;
                &lt;div class="col-md-6"&gt;
                    &lt;textarea id="descricao" name="descricao" class="form-control" rows="15"&gt;&lt;/textarea&gt;
                &lt;/div&gt;
                &lt;div class="col-md-3"&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="row"&gt;
                &lt;div class="col-md-3"&gt;&lt;/div&gt;
                &lt;div class="col-md-6"&gt;&lt;/div&gt;
                &lt;div class="col-md-3"&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="row"&gt;
                &lt;div class="col-md-3"&gt;
                    &lt;h3&gt;&lt;label for="parent.pagina.id" class="label label-default"&gt;pagina&lt;/label&gt;&lt;/h3&gt;
                &lt;/div&gt;
                &lt;div class="col-md-6"&gt;
  
                        &lt;select id="parent.pagina.id" name="parent.pagina.id" class="form-control select" data-lista="/loja/Pagina/listagem2.json"&gt;&lt;/select&gt;
  
  
                &lt;/div&gt;
                &lt;div class="col-md-3"&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="row"&gt;
                &lt;div class="col-md-3"&gt;
                    &lt;h3&gt;&lt;label for="parent.produto.id" class="label label-default"&gt;produto&lt;/label&gt;&lt;/h3&gt;
                &lt;/div&gt;
                &lt;div class="col-md-6"&gt;
  
  
                        &lt;select id="parent.produto.id" name="parent.produto.id" class="form-control select" data-lista="/loja/Produto/listagem2.json"&gt;&lt;/select&gt;
  
                &lt;/div&gt;
                &lt;div class="col-md-3"&gt;&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="panel panel-default"&gt;
                &lt;div class="panel-heading"&gt;imagem da capa (jpeg, 1280x250)&lt;/div&gt;
                &lt;div class="panel-body"&gt;
                    &lt;input type="file" name="file" class="form-control"&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;button type="submit" class="btn btn-lg btn-primary"&gt;cadastrar&lt;/button&gt;
    &lt;/form&gt;
  </code></pre>
  
  <p><em>controller</em></p>
  
  <pre><code>@RequestMapping(value="cadastra", method=RequestMethod.POST)
  @ResponseBody
  public String cadastra(@ModelAttribute("object") E object, BindingResult result, @RequestParam(value="file", required=false) MultipartFile file, @RequestParam(value="icone", required=false) MultipartFile icone) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
      serv.cadastra(object);
      serv.upload_picture(object, file, "picture");
      serv.upload_picture(object, icone, "icone");
      return "";
  }
  </code></pre>
  
  <p><em>service class</em></p>
  
  <pre><code>@PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
  @Transactional
  public void cadastra(E e) {
      dao.persist(e);
  }
  </code></pre>
  
  <p><em>Dao class</em></p>
  
  <pre><code>@Transactional
  public void persist(E transientInstance) {
      sessionFactory.getCurrentSession().persist(transientInstance);
  }
  </code></pre>