Boa tarde, ontem conversando com o Fernando o instrutor aqui da alura, ele me tiro dúvidas em uso de cascade, mais e sem o uso do cascade como que faz para adicionar um atribudo que tem 2 fk? porque estou querendo salvar o item no banco e não aceita de jeito nenhum o hibernate me acusa erro, quando não acusa me fala do atributo null.
@Entity
@SuppressWarnings("serial")
public class Item implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long codigo;
private Integer quantidade;
private BigDecimal valorParcial = BigDecimal.valueOf(0.0D);
@ManyToOne
@JoinColumn(name = "produto_codigo")
private Produto produto = new Produto();
@ManyToOne
@JoinColumn(name = "venda_codigo")
private Venda venda = new Venda();
@Entity
@SuppressWarnings("serial")
public class Venda implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long codigo;
@Temporal(TemporalType.TIMESTAMP)
private Calendar horario = Calendar.getInstance();
private BigDecimal valorTotal = BigDecimal.valueOf(0.0D);
@ManyToOne
@JoinColumn(name = "funcionario_codigo")
private Funcionario funcionario = new Funcionario();
@OneToMany(mappedBy = "venda")
private List<Item> itens = new ArrayList<Item>();
Quando faço o meu código para salvar desse jeito.
@Transacao
public void salvar() {
if (venda.getCodigo() == null) {
Funcionario buscarPorId = funcionarioDao.buscarPorId(venda.getFuncionario().getCodigo());
venda.setFuncionario(buscarPorId);
vendaDao.salvar(venda);
mensagem.mensagem("Venda efetuada com sucesso");
} else {
}
this.venda = new Venda();
this.itens = new ArrayList<Item>();
}
Ocorre tudo perfeito, porém queria salvar os meus itens também e não só a venda. Agora quando vo adiconar minha venda assim sem passar a referecia do produto, me retorna o erro.
@Transacao
public void salvar() {
if (venda.getCodigo() == null) {
Funcionario buscarPorId = funcionarioDao.buscarPorId(venda.getFuncionario().getCodigo());
venda.setFuncionario(buscarPorId);
vendaDao.salvar(venda);
itemDao.salvar(item);
mensagem.mensagem("Venda efetuada com sucesso");
} else {
}
this.venda = new Venda();
this.itens = new ArrayList<Item>();
}
fev 01, 2017 6:22:41 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:92)
at br.com.bercalini.gerenciamento.Gerenciamento.gerenciarTransacoes(Gerenciamento.java:25)
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.jboss.weld.interceptor.reader.SimpleInterceptorInvocation$SimpleMethodInvocation.invoke(SimpleInterceptorInvocation.java:74)
at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeAroundInvoke(InterceptorMethodHandler.java:84)
at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeInterception(InterceptorMethodHandler.java:72)
at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.invoke(InterceptorMethodHandler.java:56)
at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:79)
at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:68)
at br.com.bercalini.bean.VendaBean$Proxy$_$$_WeldSubclass.salvar(Unknown Source)
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.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:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
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:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
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:141)
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:509)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
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: java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing: br.com.bercalini.modelo.Item.produto -> br.com.bercalini.modelo.Produto
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1374)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:80)
... 51 more
Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing: br.com.bercalini.modelo.Item.produto -> br.com.bercalini.modelo.Produto
at org.hibernate.engine.spi.CascadingAction$8.noCascade(CascadingAction.java:380)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:176)
at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:160)
at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:151)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:88)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1213)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:402)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:75)
... 51 more
Porém quando faço a minha referencia.
@Transacao
public void salvar() {
if (venda.getCodigo() == null) {
Funcionario buscarPorId = funcionarioDao.buscarPorId(venda.getFuncionario().getCodigo());
venda.setFuncionario(buscarPorId);
vendaDao.salvar(venda);
Produto buscarPorId2 = produtoDao.buscarPorId(item.getProduto().getCodigo());
item.setProduto(buscarPorId2);
itemDao.salvar(item);
mensagem.mensagem("Venda efetuada com sucesso");
} else {
}
this.venda = new Venda();
this.itens = new ArrayList<Item>();
}
O erro do null, mais sinceramente não to entendendo o erro null
ADVERTÊNCIA: java.lang.IllegalArgumentException: id to load is required for loading
javax.el.ELException: java.lang.IllegalArgumentException: id to load is required for loading
at org.apache.el.parser.AstValue.invoke(AstValue.java:260)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
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:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
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:141)
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:509)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
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: java.lang.IllegalArgumentException: id to load is required for loading
at org.hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:87)
at org.hibernate.event.spi.LoadEvent.<init>(LoadEvent.java:59)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2421)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:974)
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:807)
at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:781)
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.jboss.weld.bean.proxy.AbstractBeanInstance.invoke(AbstractBeanInstance.java:38)
at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:100)
at org.jboss.weldx.persistence.EntityManager$196817612$Proxy$_$$_WeldClientProxy.find(Unknown Source)
at br.com.bercalini.dao.ProdutoDao.buscarPorId(ProdutoDao.java:41)
at br.com.bercalini.bean.VendaBean.salvar(VendaBean.java:51)
at br.com.bercalini.bean.VendaBean$Proxy$_$$_WeldSubclass.salvar$$super(Unknown Source)
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.jboss.weld.interceptor.proxy.TerminalAroundInvokeInvocationContext.proceedInternal(TerminalAroundInvokeInvocationContext.java:49)
at org.jboss.weld.interceptor.proxy.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:77)
at br.com.bercalini.gerenciamento.Gerenciamento.gerenciarTransacoes(Gerenciamento.java:24)
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.jboss.weld.interceptor.reader.SimpleInterceptorInvocation$SimpleMethodInvocation.invoke(SimpleInterceptorInvocation.java:74)
at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeAroundInvoke(InterceptorMethodHandler.java:84)
at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeInterception(InterceptorMethodHandler.java:72)
at org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.invoke(InterceptorMethodHandler.java:56)
at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:79)
at org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:68)
at br.com.bercalini.bean.VendaBean$Proxy$_$$_WeldSubclass.salvar(Unknown Source)
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.apache.el.parser.AstValue.invoke(AstValue.java:247)
... 34 more
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<ui:composition template="/template/template.xhtml">
<ui:define name="conteudo">
<div class="ui-fluid">
<h:form id="formularioVenda">
<p:growl id="mensagem" showDetail="true" sticky="true" />
<p:dataTable id="tabelaVenda" paginator="true" rows="3"
emptyMessage="Nenhum produto encontrado" var="produto"
value="#{vendaBean.listaProdutos}">
<f:facet name="header">
Tabela de produtos
</f:facet>
<p:column headerText="Produto">
<h:outputText value="#{produto.nome}" />
</p:column>
<p:column headerText="Preço">
<h:outputText value="#{produto.preco}" />
</p:column>
<p:column headerText="Quantidade">
<h:outputText value="#{produto.quantidade}" />
</p:column>
<p:column headerText="Fornecedor">
<h:outputText value="#{produto.fornecedor.nome}" />
</p:column>
<p:column headerText="Adicionar Item">
<p:commandButton value="Adicionar"
actionListener="#{vendaBean.adicionarProduto(produto)}"
update=":formularioVenda:tblItens :formularioVenda:painelVenda" />
</p:column>
</p:dataTable>
<p:separator />
<p:dataTable id="tblItens" paginator="true" rows="3"
emptyMessage="Nenhum item encontrado" var="item"
value="#{vendaBean.itens}">
<p:column headerText="Produto">
<h:outputText value="#{item.produto.nome}" />
</p:column>
<p:column headerText="Quantidade">
<h:outputText value="#{item.quantidade}" />
</p:column>
<p:column headerText="Valor Parcial">
<h:outputText value="#{item.valorParcial}" />
</p:column>
<p:column headerText="Fornecedor">
<h:outputText value="#{item.produto.fornecedor.nome}" />
</p:column>
<p:column headerText="Remover Item">
<p:commandButton value="Remover"
actionListener="#{vendaBean.remover(item)}"
update=":formularioVenda:tblItens :formularioVenda:painelVenda" />
</p:column>
</p:dataTable>
<h:panelGrid columns="3" id="painelVenda">
<p:outputLabel value="Valor total: " for="valor" />
<p:inputText id="valor" value="#{vendaBean.venda.valorTotal}"
readonly="true" size="11" />
<p:commandButton value="Finalizar venda"
actionListener="#{vendaBean.carregarDadosVenda}"
oncomplete="PF('finalizar').show();"
update=":formularioVenda :dialog" />
</h:panelGrid>
</h:form>
<p:dialog id="dialog" appendTo="@(body)" header="Finalizar venda"
closable="true" modal="true" resizable="false" draggable="false"
widgetVar="finalizar">
<h:form>
<h:panelGrid columns="2">
<p:outputLabel value="Data: " />
<p:inputText readonly="true"
value="#{vendaBean.venda.horario.time}">
<f:convertDateTime pattern="dd/MM/yyyy"
timeZone="America/Sao_Paulo" />
</p:inputText>
<p:outputLabel value="Funcionario: " />
<p:inputText readonly="true"
value="#{vendaBean.venda.funcionario.nome}" />
<p:outputLabel value="Valor total: " />
<p:inputText readonly="true" value="#{vendaBean.venda.valorTotal}" />
<p:commandButton value="Finalizar"
actionListener="#{vendaBean.salvar}" update="formularioVenda"
onclick="PF('finalizar').hide();" />
<p:commandButton value="Voltar" onclick="PF('finalizar').hide();" />
</h:panelGrid>
</h:form>
</p:dialog>
</div>
</ui:define>
</ui:composition>
</html>