Inject Dao into Converter

Asked

Viewed 300 times

2

I’m having a java.lang.Nullpointerexception error in a Converter at the moment it will access the bank, apparently the dependency is not being injected by the CDI, there are arguments that the Converter should not access the Bank anymore in my case I am not able to make the view with a Dialogo do Primefaces work, without the Dialogo it works, with it not so why the Converter changed, more how to make it work?

Project with JSF 2.2 + CDI + JPA, in Tomcat 8 Java 8 I’ve seen Converter with Dao’s injection only that I’m not succeeding the mistake is Caused by: java.lang.Nullpointerexception at br.com.dominio.converter.Estadoconverter.getAsObject(Estadoconverter.java:29) I don’t know if in projects I’ve seen this kind of conversion has.... let’s say the data ( Entitymanager in session ) will see that the instance being created plus Entitymanager is the problem?

Follow the MB

@Named(value = "municipioC")
@ViewScoped
public class MunicipioController extends AbstractMB {

    private static final long serialVersionUID = 1L;

    private int totalRegistros;
    private List<Municipio> elementos;
    private List<Estado> estados;
    private Municipio registroSelecionado;
    private Municipio municipio;

    @Inject
    private MunicipioService municipioService;

    @Inject
    private EstadoService estadoService;

    public MunicipioController() {
    }
}

Follows the Converter

FacesConverter(forClass = Estado.class)
public class EstadoConverter implements Converter {

    @Inject
    EstadoDao dao ;

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {

    System.out.println("EstadoConverter - getAsObject - valor: "+value);        

    Estado estado = null;

    if (StringUtils.isNotEmpty(value)){
        Integer Id = Integer.parseInt(value);
        // Na linha Abaixo ocorre o erro 
        estado = this.dao.findByID(Id);
    }

    return estado;
}

and the view

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
template="/WEB-INF/templates/Layout.xhtml">

<ui:define name="content">
    <h1 class="aw-page-title">Municípios</h1>

    <h:form id="frm">

        <p:toolbar>
            <p:toolbarGroup>
                <p:commandButton id="btnAdd" title="Novo registro"
                    action="#{municipioC.preparaInclusao}"
                    oncomplete="PF('itemDialog').show()" process="@this"
                    update=":itemForm:itemPanel" icon="fa fa-fw fa-plus" />

                <p:commandButton id="btnEdi" title="Edita registro"
                    action="#{municipioC.preparaAlteracao}"
                    oncomplete="PF('itemDialog').show()" process="@this"
                    update=":itemForm:itemPanel" icon="fa fa-fw fa-edit" />

            </p:toolbarGroup>
        </p:toolbar>

        <p:messages autoUpdate="false" />
        <p:dataTable id="itensTable" widgetVar="dataTable" var="item"
            loadingMessage="Carregando..." emptyMessage="Nenhum registro."
            reflow="true" value="#{municipioC.elementos}" selectionMode="single"
            selection="#{municipioC.registroSelecionado}"
            rowKey="#{item.id}" style="margin-top:10px">

            <p:ajax event="rowSelect" listener="#{municipioC.selectRegistro}" />

            <p:column headerText="Id" style="width:50px">
                <h:outputText value="#{item.id}" />
            </p:column>

            <p:column headerText="Municipio">
                <h:outputText value="#{item.dsMunicipio}" />
            </p:column>

            <p:column headerText="Uf">
                <h:outputText value="#{item.estado.siglaEstado}" />
            </p:column>

        </p:dataTable>
    </h:form>

    <p:dialog widgetVar="itemDialog" id="iditemDialog" header="Gerencia municipios"
        responsive="true" resizable="false" showEffect="explode"
        hideEffect="bounce" style="min-width: 400px" modal="true" appendTo="@(body)">

        <h:form id="itemForm">

            <h:panelGroup id="itemPanel" layout="block" styleClass="ui-fluid"
                style="margin-top:10px;">
                <p:messages id="msgDialog" autoUpdate="false" />

                <p:panelGrid columns="2" layout="grid"
                    styleClass="panelgrid-noborder"
                    columnClasses="ui-grid-col-4, ui-grid-col-8">

                    <p:outputLabel for="nome" value="Municipio:" />
                    <p:inputText id="nome" value="#{municipioC.municipio.dsMunicipio}"
                        placeholder="Municipio" size="50" />
                    <p:outputLabel for="ibge" value="Codigo IBGE:" />
                    <p:inputText id="ibge" value="#{municipioC.municipio.codIbge}"
                        placeholder="Codigo IBGE" size="10" />

                    <p:outputLabel for="estado" value="Estado" />
                    <p:selectOneMenu id="estado"
                        value="#{municipioC.municipio.estado}" required="true">
                        <f:selectItem itemLabel="Selecione" />
                        <f:selectItems value="#{municipioC.estados}" var="itemE"
                            itemValue="#{itemE}" itemLabel="#{itemE.dsEstado}" />
                    </p:selectOneMenu>

                </p:panelGrid>

            </h:panelGroup>

            <p:commandButton icon="fa fa-fw fa-save" title="Salvar"
                        action="#{municipioC.salvar}" process="itemPanel"
                        update="itemPanel"
                        oncomplete="closeDialogIfSucess(xhr, status, args, PF('itemDialog'), 'itemDialog')" />

        </h:form>
    </p:dialog>

</ui:define>

1 answer

0

Unfortunately the @Inject does not work with the annotation @FacesConverter.

There are other ways to solve this problem. One is to replace the annotation:

@FacesConverter(forClass = Estado.class)

for

@Named

and use

<p:selectOneMenu converter="#{estadoConverter}" />

Another way would be to use the bilbiotec Omnifaces, that since version 1.6 has support for @Inject in a @FacesConverter.


For more details, see this full answer of @Balusc.

  • Marcelo thanks for the interaction, I used Omnifaces and continued the problem so I understand that the injection could even be being made the bid so would be the Entitymanager or when accessing the bank and make the query. I then changed my class Estado.java commented //bi-Directional Many-to-one Association to Municipio //@Onetomany(mappedBy="status") //private List<Municipio> municipios and in Municipio.java I retired //@Manytoone(fetch=Fetchtype.LAZY) Just @Manytoone and everything is okay, could you comment? with Spring I used openEntityManagerInViewFilter now have only CDI

  • Just one detail about Omnifaces: the documentation comments on annotating the beans.xml for bean-discovery-mode="all". Generally the one used is bean-discovery-mode="annotated". You really have to make the change to make it work.

Browser other questions tagged

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