Error saving related entities - Unsave Transient instance

Asked

Viewed 761 times

1

A subsidiary owns a product - relationship @OneToOne - and one product has several historical.

Method of registering implemented:

public class CadastroProdutoService implements Serializable {

private static final long serialVersionUID = 1L;

@Inject
private Produtos produtos;

@Transactional
public void salvar(Produto produto) {
    Produto produtoExistente = produtos.porCodigo(produto);
    if (produtoExistente != null && !produtoExistente.equals(produto)) {
        produtos.remover(produtoExistente);

    }

    try {
        this.produtos.guardar(produto);
    } catch (OptimisticLockException e) {

        throw new NegocioException(FacesUtil.getMensagemI18n("concorrencia_familia"));

    }

}

}

The product table is as follows:

public class Produto implements Serializable {

    private static final long serialVersionUID = 1L;
    public final static String ALL = "produto.populaproduto";
    public final static String COUNT = "produto.countprodutoTotal";
    public final static String DESCRICAO = "produto.descricao";

    private Long codigo;

    private Integer Version;

    private String codigoProduto;

    private String descricao;

    private BigDecimal valor;

    private Empresa empresa;

    private Linha linha;

    private Usuario gerenteFilial;

    private Double fatorAmortecimentoExponencial;

    private Long quantidadeRecente;

    private BigDecimal quantidadeReais;

    private List<Historico> historicos = new ArrayList<>();

    @OneToMany(mappedBy = "produto", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    public List<Historico> getHistoricos() {
        return historicos;
    }

    public void setHistoricos(List<Historico> historicos) {
        this.historicos = historicos;
    }

    public Produto() {
    }

    public Produto(String codigoProduto, String descricao, BigDecimal valor) {
        this.codigoProduto = codigoProduto;
        this.descricao = descricao;
        this.valor = valor;
    }

    @Version
    public Integer getVersion() {
        return Version;
    }

    public void setVersion(Integer version) {
        Version = version;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getCodigo() {
        return codigo;
    }

    public void setCodigo(Long codigo) {
        this.codigo = codigo;
    }

    @NotBlank
    @Column(nullable = false, length = 50)
    public String getCodigoProduto() {
        return codigoProduto;
    }

    public void setCodigoProduto(String codigoProduto) {
        this.codigoProduto = codigoProduto;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao == null ? null : descricao.toUpperCase().trim();

    }

    @NotBlank
    @Column(nullable = false, length = 100)
    public String getDescricao() {
        return descricao;
    }

    @Column(name = "valor", nullable = false, precision = 10, scale = 2)
    public BigDecimal getValor() {
        return valor;
    }

    public void setValor(BigDecimal valor) {
        this.valor = valor;
    }

    @Column(name = "fatorAmortecimentoExponencial", nullable = true, precision = 10, scale = 2)
    public Double getFatorAmortecimentoExponencial() {
        return fatorAmortecimentoExponencial;
    }

    public void setFatorAmortecimentoExponencial(Double fatorAmortecimentoExponencial) {
        this.fatorAmortecimentoExponencial = fatorAmortecimentoExponencial;
    }

    @Column(name = "quantidade_recente")
    public Long getQuantidadeRecente() {
        return quantidadeRecente;
    }

    public void setQuantidadeRecente(Long quantidadeRecente) {
        this.quantidadeRecente = quantidadeRecente;
    }

    @Column(name = "quantidade_reais", nullable = true, precision = 10, scale = 2)
    public BigDecimal getQuantidadeReais() {
        return quantidadeReais;
    }

    public void setQuantidadeReais(BigDecimal quantidadeReais) {
        this.quantidadeReais = quantidadeReais;
    }

    @ManyToOne
    @JoinColumn(name = "codigo_empresa")
    public Empresa getEmpresa() {
        return empresa;
    }

    public void setEmpresa(Empresa empresa) {
        this.empresa = empresa;
    }

    @OneToOne
    @JoinColumn(name = "codigo_linha")
    public Linha getLinha() {
        return linha;
    }

    public void setLinha(Linha linha) {
        this.linha = linha;
    }

    @ManyToOne
    @JoinColumn(name = "codigo_filial")
    public Usuario getGerenteFilial() {
        return gerenteFilial;
    }

    public void setGerenteFilial(Usuario gerenteFilial) {
        this.gerenteFilial = gerenteFilial;
    }

By persisting product:

Double alfa = BigDecimal.valueOf((fatorAmortecimentoExponencial(arrayComUltimosCincoMeses)))
                        .setScale(3, RoundingMode.HALF_UP).doubleValue();

                System.out.println("Alfa " + alfa);
                System.out.println("Melhor taxa: " + alfa + " - resultado: "
                        + Math.round(calculoPrevisao(alfa.doubleValue(), arrayComQuantidades)));
                Long previsao = Math.round(calculoPrevisao(alfa.doubleValue(), arrayComQuantidades));

                listaComCincoUltimosMeses.clear();
                listaComQuantidade.clear();
                prod.setEmpresa(empresaSelecionada);
                prod.setGerenteFilial(gerenteFilial);
                prod.setFatorAmortecimentoExponencial(alfa);
                prod.setQuantidadeRecente(previsao);
                prod.setQuantidadeReais(prod.getValor().multiply(new BigDecimal(previsao)));
                cadastroProdutoService.salvar(prod);// persistir após
                                                    // calcular o
                                                    // alfa

The following error occurs:

   Hibernate: 
    insert 
    into
        produto
        (codigoProduto, descricao, codigo_empresa, fatorAmortecimentoExponencial, codigo_filial, codigo_linha, quantidade_reais, quantidade_recente, valor, version) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
Hibernate: 
    insert 
    into
        historico
        (meses_historicos, id_produto, quantidade, version) 
    values
        (?, ?, ?, ?)
jun 07, 2017 9:47:43 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: #{fileBean.send}: javax.persistence.RollbackException: Error while committing the transaction
javax.faces.FacesException: #{fileBean.send}: javax.persistence.RollbackException: Error while committing the transaction
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:117)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    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.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:54)
    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:183)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
    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:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:96)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    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)
Caused by: javax.faces.el.EvaluationException: javax.persistence.RollbackException: Error while committing the transaction
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
    ... 61 more
Caused by: javax.persistence.RollbackException: Error while committing the transaction
    at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:94)
    at br.com.previsao.util.jpa.TransactionInterceptor.invoke(TransactionInterceptor.java:47)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.__invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.weld.interceptor.proxy.SimpleMethodInvocation.invoke(SimpleMethodInvocation.java:30)
    at org.jboss.weld.interceptor.proxy.SimpleInterceptionChain.invokeNextInterceptor(SimpleInterceptionChain.java:69)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeInterception(InterceptorMethodHandler.java:112)
    at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.invoke(InterceptorMethodHandler.java:88)
    at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:55)
    at br.com.previsao.service.CadastroProdutoService$Proxy$_$$_WeldSubclass.salvar(CadastroProdutoService$Proxy$_$$_WeldSubclass.java)
    at br.com.previsao.controller.FileBean.send(FileBean.java:204)
    at br.com.previsao.controller.FileBean$Proxy$_$$_WeldClientProxy.send(FileBean$Proxy$_$$_WeldClientProxy.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.__invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 62 more
Caused by: java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : br.com.previsao.model.Produto.linha -> br.com.previsao.model.Linha
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1760)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
    at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:82)
    ... 89 more
Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : br.com.previsao.model.Produto.linha -> br.com.previsao.model.Linha
    at org.hibernate.engine.spi.CascadingActions$8.noCascade(CascadingActions.java:398)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:129)
    at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:167)
    at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:158)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:91)
    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.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
    ... 89 more
  • has ever received this Exception?

  • mappeei as list in other table and received another error Caused by: java.lang.Illegalargumentexception: Unknown Entity: br.com.previsao.model.Line

  • @Williamcézar Beware of formatting stacktraces - https://pt.meta.stackoverflow.com/a/5360/132

  • What’s in the class Linha? What’s in the method cadastroProdutoService.salvar(prod);?

  • @Victorstafusa thanks for the information, I will take more care of the next times.

1 answer

1


Try to change that:

@OneToOne
@JoinColumn(name = "codigo_linha")
public Linha getLinha() {
    return linha;
}

For that reason:

@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "codigo_linha")
public Linha getLinha() {
    return linha;
}

Note the differences in the annotation of @OneToOne.

  • It worked, but by doing this duplicates the rows in the row table I want it in the product table https://snag.gy/cPpC5J.jpg

  • @user2509556 - Your screenshot didn’t open here for me. To try to get a better answer, edit the question and put what’s in the class Linha and what’s in the method cadastroProdutoService.salvar(prod).

  • I did it differently. instead of importing the line from an xml file and saving it as it was doing, and so Scade, now I’m associating the line to the product on a screen and solved the problem. I appreciate the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.