not-null Property References a null or Transient value

Asked

Viewed 2,005 times

0

When I try to save a city, it shows not-null error, but looking, I can’t find a solution when looking for the controller, I understand the error, but in my project.

Caused by: org.hibernate.Propertyvalueexception: not-null Property References a null or Transient value : com.pi.drogaria.model.entidades.Cidade.estado

Model:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int codigoCidade;

@Column(length = 50, nullable = false)
private String nome;

@ManyToOne
@JoinColumn(nullable = false)
private Estado estado;

public int getCodigoCidade() {
    return codigoCidade;
}

public void setCodigoCidade(int codigoCidade) {
    this.codigoCidade = codigoCidade;
}

public String getNome() {
    return nome;
}

public void setNome(String nome) {
    this.nome = nome;
}

public Estado getEstado() {
    return estado;
}

public void setEstado(Estado estado) {
    this.estado = estado;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + codigoCidade;
    result = prime * result + ((estado == null) ? 0 : estado.hashCode());
    result = prime * result + ((nome == null) ? 0 : nome.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Cidade other = (Cidade) obj;
    if (codigoCidade != other.codigoCidade)
        return false;
    if (estado == null) {
        if (other.estado != null)
            return false;
    } else if (!estado.equals(other.estado))
        return false;
    if (nome == null) {
        if (other.nome != null)
            return false;
    } else if (!nome.equals(other.nome))
        return false;
    return true;
}

XHMTL:

<ui:define name="conteudo">

    <h:form id="formListagem">

        <p:panel header="Cidades - Listagem">

            <p:dataTable id="tabela" emptyMessage="Nenhum registro encontrado."
                paginator="true" value="#{cidadeController.cidades}" var="cidade"
                rows="5" paginatorPosition="top">

                <f:facet name="header">

                    <p:commandButton value="Novo" actionListener="#{cidadeController.novo()}"
                        oncomplete="PF('dialogo').show();"
                        update=":mensagem :formCadastro:painel">

                        <f:actionListener
                            type="org.omnifaces.eventlistener.ResetInputAjaxActionListener" />

                    </p:commandButton>

                </f:facet>

                <p:column headerText="Nome" filterBy="#{cidade.nome}"
                    sortBy="#{cidade.nome}">

                    <h:outputText value="#{cidade.nome}" />

                </p:column>

                <p:column headerText="Estado" filterBy="#{cidade.estado.nome}"
                    sortBy="#{cidade.estado.nome}">

                    <h:outputText value="#{cidade.estado.nome}" />

                    <h:outputText value=" - " />

                    <h:outputText value="#{cidade.estado.sigla}" />

                </p:column>

                <p:column headerText="Opções">

                    <p:commandButton icon="ui-icon-trash"
                        actionListener="#{cidadeController.excluir()}"
                        update=":mensagem :formListagem:tabela">

                        <p:confirm header="Confirmação" message="Deseja excluir a cidade"
                            icon="ui-icon-alert" />

                        <f:attribute name="cidadeSelecionada" value="#{cidade}" />

                    </p:commandButton>

                    <p:commandButton icon="ui-icon-pencil"
                        actionListener="#{cidadeController.editar()}"
                        update=":mensagem :formCadastro:painel"
                        oncomplete="PF('dialogo').show();">

                        <f:attribute name="cidadeSelecionada" value="#{cidade}" />

                        <f:actionListener
                            type="org.omnifaces.eventlistener.ResetInputAjaxActionListener" />

                    </p:commandButton>

                </p:column>

            </p:dataTable>

            <p:confirmDialog global="true">

                <p:commandButton value="Sim" type="button"
                    styleClass="ui-confirmdialog-yes" icon="ui-icon-check" />

                <p:commandButton value="Não" type="button"
                    styleClass="ui-confirmdialog-no" icon="ui-icon-close" />

            </p:confirmDialog>

        </p:panel>

    </h:form>

    <p:dialog header="Cidades - Cadastro" widgetVar="dialogo"
        draggable="false" resizable="false" modal="true" closable="false">

        <h:form id="formCadastro">

            <h:panelGrid id="painel" columns="2">

                <p:outputLabel for="nome" value="Nome:" />

                <p:inputText id="nome" maxlength="50" size="30"
                    value="#{cidadeController.cidade.nome}" required="true"
                    requiredMessage="O campo NOME é obrigatório" />

                <p:outputLabel for="estado" value="Estado:" />

                <p:selectOneMenu id="estado" filter="true"
                    value="#{cidadeController.cidade.estado}"
                    converter="omnifaces.SelectItemsConverter" required="true"
                    requiredMessage="O campo ESTADO é obrigatório">

                    <f:selectItem noSelectionOption="true"
                        itemLabel="Selecione um estado" />

                    <f:selectItems value="#{cidadeController.estados}" var="estado"
                        itemValue="#{estado}"
                        itemLabel="#{estado.nome} - #{estado.sigla}" />

                </p:selectOneMenu>

            </h:panelGrid>

            <h:panelGrid columns="2">

                <p:commandButton value="Salvar"
                    actionListener="#{cidadeController.salvar()}"
                    update=":mensagem :formCadastro:painel :formListagem:tabela" />

                <p:commandButton value="Fechar" oncomplete="PF('dialogo').hide();" />

            </h:panelGrid>

        </h:form>

    </p:dialog>

Console error:

javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value : com.pi.drogaria.model.entidades.Cidade.estado
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:913)
at org.hibernate.internal.SessionImpl.merge(SessionImpl.java:887)
at com.pi.drogaria.DAO.DAOGenerico.merge(DAOGenerico.java:137)
at com.pi.drogaria.model.entidades.CidadeModel.salvar(CidadeModel.java:22)
at com.pi.drogaria.controller.CidadeController.salvar(CidadeController.java:85)
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 com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:147)
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:94)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1152)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495)
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: org.hibernate.PropertyValueException: not-null property references a null or transient value : com.pi.drogaria.model.entidades.Cidade.estado
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:108)
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:56)
at org.hibernate.action.internal.AbstractEntityInsertAction.nullifyTransientReferencesIfNotAlready(AbstractEntityInsertAction.java:115)
at org.hibernate.action.internal.AbstractEntityInsertAction.makeEntityManaged(AbstractEntityInsertAction.java:124)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:289)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:250)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:367)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:292)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:200)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:143)
at org.hibernate.event.internal.DefaultMergeEventListener.saveTransientEntity(DefaultMergeEventListener.java:255)
at org.hibernate.event.internal.DefaultMergeEventListener.entityIsTransient(DefaultMergeEventListener.java:235)
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:173)
at org.hibernate.event.internal.DefaultMergeEventListener.onMerge(DefaultMergeEventListener.java:69)
at org.hibernate.internal.SessionImpl.fireMerge(SessionImpl.java:901)
... 42 more

Citizen:

public class CidadeController implements Serializable {
private Cidade cidade;
private List<Cidade> cidades;
private List<Estado> estados;

public Cidade getCidade() {
    return cidade;
}

public void setCidade(Cidade cidade) {
    this.cidade = cidade;
}

public List<Cidade> getCidades() {
    return cidades;
}

public void setCidades(List<Cidade> cidades) {
    this.cidades = cidades;
}

public List<Estado> getEstados() {
    return estados;
}

public void setEstados(List<Estado> estados) {
    this.estados = estados;
}

@PostConstruct
public void listar() {
    try {
        CidadeModel cidadeModel = new CidadeModel();

        this.setCidades(cidadeModel.listar());

    } catch (Exception ex) {
        Messages.addFlashGlobalError("Ocorreu um erro ao tentar listar as cidades");
        ex.printStackTrace();
    }
}

public void novo() {
    try {
        cidade = new Cidade();

        EstadoDAO estadoDAO = new EstadoDAO();
        List<Object> estados = estadoDAO.listar("nome", Estado.class);

        List<Estado> states = getListEstado(estados);
        this.setEstados(states);

    } catch (Exception ex) {
        Messages.addFlashGlobalError("Ocorreu um erro ao gerar uma nova cidade");
        ex.printStackTrace();
    }
}

public void salvar() {
    try {
        CidadeModel cidadeModel = new CidadeModel();

        this.setCidades(cidadeModel.salvar(cidade));

        EstadoDAO estadoDAO = new EstadoDAO();
        List<Object> estados = estadoDAO.listar(Estado.class);

        List<Estado> states = getListEstado(estados);
        this.setEstados(states);

        cidade = new Cidade();

        Messages.addGlobalInfo("Cidade salva com sucesso");
    } catch (Exception ex) {
        Messages.addFlashGlobalError("Ocorreu um erro ao tentar salvar uma nova cidade");
        ex.printStackTrace();
    }
}

private List<Estado> getListEstado(List<Object> estados) {
    List<Estado> states = new ArrayList<>();

    for (Object obj : estados) {
        states.add((Estado) obj);
    }
    return states;
}

private List<Cidade> getListCidade(List<Object> cidades) {
    List<Cidade> city = new ArrayList<>();

    for (Object obj : cidades) {
        city.add((Cidade) obj);
    }
    return city;
}

public void excluir(ActionEvent evento) {
    try {
        cidade = (Cidade) evento.getComponent().getAttributes().get("cidadeSelecionada");

        CidadeModel cidadeModel = new CidadeModel();
        this.setCidades(cidadeModel.excluir(cidade));

        Messages.addGlobalInfo("Cidade removida com sucesso");
    } catch (Exception ex) {
        Messages.addFlashGlobalError("Ocorreu um erro ao tentar remover a cidade");
        ex.printStackTrace();
    }
}

public void editar(ActionEvent evento) {
    try {
        cidade = (Cidade) evento.getComponent().getAttributes().get("cidadeSelecionada");

        CidadeModel cidadeModel = new CidadeModel();
        this.setCidades(cidadeModel.editar(cidade));

    } catch (Exception ex) {
        Messages.addFlashGlobalError("Ocorreu um erro ao tentar selecionar uma cidade");
        ex.printStackTrace();
    }

}
  • Vc saw if the entity has the values set correctly before persisting (no CidadeController.salvar)?

  • @Marcusmartins I think this is correct, I put my Citadel, for you to see if can help in this.

  • Put a breakpoint on the line of this.setCidades(cidadeModel.salvar(cidade)) to see if the object cidade is with all values set. I’m guessing he’s not in the set state at the time of persisting. May be bug in convert omnifaces.Selectitemsconverter.

  • @Marcusmartins put and still gets this error "not-null Property References a null or Transient value : com.pi.drogaria.model.entidades.Cidade.estado"

  • But checked if the city object is at all values set?

  • @Marcusmartins discovered the problem, is that every time I modified something in the controller, my project or the eclipse, I didn’t update the changes, so I did a Maven install and took it... thanks anyway.

Show 1 more comment

1 answer

3

Basically, you are calling a persist in the City entity that has the state attribute set to nullable = false, therefore, if you do not define this attribute, JPA / Hibernate will not allow you to save it in the database.

Browser other questions tagged

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